I have a collection of products and another on the replacement of stock of the product. What I'm looking for is that when you get the products, all the product's stock dates 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 current 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 attempt to join the objects
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
});
});
});
Another way I've seen is to make a push
to the Products model, but I can not make it work either.