Search code examples
node.jsmongoosemongoose-populate

Mongoose connect two collections


I have a collection of products, and another on the reposition of stock of the product. What I'm looking for is that when I get the products, all the replenishment dates and the new stock appear, something like this:

{
  "ok": true,
  "producto": {
    "repo": [
    {
            "_id": "5ac643ab88b5a132384f7758",
            "restock": 22,
            "date": "2018-03-04T03:00:00.000Z",
            "producto": "5ac6433588b5a132384f7757",
            "__v": 0
        },
        {
            "_id": "5ac6470079b67f39985ffe3c",
            "restock": 44,
            "date": "2018-04-04T03:00:00.000Z",
            "producto": "5ac6433588b5a132384f7757",
            "__v": 0
        }
    ],
    "_id": "5ac6433588b5a132384f7757",
    "nombre": "Vianda Vegetariana",
    "usuario": "5ac546f293e2b932a47b5f43",
    "createdAt": "2018-04-05T15:39:33.911Z",
    "updatedAt": "2018-04-05T15:39:33.911Z",
    "__v": 0
    }
}

But I only get this:

{
    "ok": true,
    "producto": {
        "repo": [],
        "_id": "5ac6433588b5a132384f7757",
        "nombre": "Vianda Vegetariana",
        "usuario": "5ac546f293e2b932a47b5f43",
        "createdAt": "2018-04-05T15:39:33.911Z",
        "updatedAt": "2018-04-05T15:39:33.911Z",
        "__v": 0
    }
}

This is my actual code:

// repo schema

var repositorSchema = new Schema({
    restock: { type: Number, required: [true, 'El restock es necesario']},
    date: { type: Date, required: true },

    producto: { type: Schema.Types.ObjectId, ref: 'Producto'},
    usuario: { type: Schema.Types.ObjectId, ref: 'Usuario', required: true }
}, { timestamps: true } );

module.exports = mongoose.model('Repositor', repositorSchema);

//product schema

var productoSchema = new Schema({
    nombre: { type: String, required: [true, 'El nombre es necesario']},
    sku: { type: String, required: false },
    repo: [{ type: Schema.Types.ObjectId, ref: 'Repositor', required: true }],
    usuario: { type: Schema.Types.ObjectId, ref: 'Usuario', required: true }
}, { timestamps: true } );

module.exports = mongoose.model('Producto', productoSchema);

My code for populate:

Producto.find({})
    .populate('repo')
    .exec(
        (err, productos)=> {
            if (err) {
                return res.status(500).json({
                    ok: false,
                    mensaje: 'Error cargando productos',
                    errors: err
                });
            }

            Producto.count({}, (err, conteo)=> {
                res.status(200).json({
                    ok: true,
                    total: conteo,
                    productos: productos
                });
            });
});

Why not working? How should populate the two?


Solution

  • I solved it in the following way. In the function to create the stock, I look for the related product and execute a push:

    app.post('/', mdAuth.verifyToken, (req, res)=>{
    
        var body = req.body;
    
        var repo = new Repo ({
            restock: body.restock,
            date: body.date,
            producto: body.producto,
            usuario: req.usuario._id
        });
    
        repo.save( (err, repoGuardado)=>{
            if (err) {
                return res.status(400).json({
                    ok: false,
                    mensaje: 'Error al crear repo',
                    errors: err
                });
            } 
    
            res.status(201).json({
                ok: true,
                repo: repoGuardado
            });
    
            /* actuializar repo en producto */
            var id = body.producto;
    
            Producto.findById( id, (err, producto)=> {
    
                if (err) {
                    return res.status(500).json({
                        ok: false,
                        mensaje: 'Error al buscar producto',
                        errors: err
                    });
                }
    
                if (!producto) {
                    return res.status(400).json({
                        ok: false,
                        mensaje: 'No existe un producto con ese ID',
                        errors: { message: 'No existe un producto con ese ID' }
                    });
                }
    
                producto.repo.push(repo);
                producto.save();
    
    
            }); /* end producto find */
    
        });
    });