I have this schema in mongoose:
var schema = new Schema({
name: {type: String, required: true},
description: {type: String, required: true},
subcategory: {type: Schema.Types.ObjectId, ref: 'SubCategory'},
price: [{type: Schema.Types.ObjectId, ref: 'Price'}],
provider: [{type: Schema.Types.ObjectId, ref: 'Provider'}]
});
var schema = new Schema({
monto: {type: Float, required: true},
fecha: {type: Date, required: true},
idProvider: {type: Schema.Types.ObjectId, ref: 'Provider'},
idProduct: {type: Schema.Types.ObjectId, ref: 'Product'}
});
I need getall products populated and I need to obtain the current price of each product and show only that. I tried doing this but doesn't work:
router.get('/', (req, res, next) => {
Product.find({})
.populate({path: 'price', options: { $sort: {'fecha': -1}, limit: 1}})
.then(product => {
if(!product) {return res.sendStatus(401);}
return res.json(product)
})
.catch(next);
})
For example:
{
"_id": "5a4eebdd24b0412d0cf58601",
"name": "Heladera",
"description": "Automatico con centrifugado",
"__v": 1,
"provider": [],
"price": [
{
"_id": "5a4ea416e723b42c28fd624e",
"monto": 8560.23,
"fecha": "2000-12-12T03:00:00.000Z",
"idProduct": "5a4ea3b3e723b42c28fd624d",
"__v": 0
}
{
"_id": "5a4f0741f722c01528582104",
"monto": 900,
"fecha": "2018-12-12T03:00:00.000Z",
"idProduct": "5a4f072ff722c01528582103",
"__v": 0
}
]
}
I need to show
{
"_id": "5a4eebdd24b0412d0cf58601",
"name": "Heladera",
"description": "Automatico con centrifugado",
"__v": 1,
"provider": [],
"price": [
{ monto: 900}
]
}