I have a Mongoose model which have paths which need to be populated :
var adsSchema = new Schema({
price: { type: Number, min: 0, required: true },
author: { type: ObjectId, ref: 'Users', required: true },
title: { type: String, required: true },
date: { type: Date, default: Date.now },
offers: [{
price: { type: Number, required: true },
date: { type: Date, default: Date.now },
offerBy: { type: ObjectId, ref: 'Users', required: true }
}],
category: { type: ObjectId },
images: [{
type: ObjectId,
ref: 'Images'
}],
videos: [String]
});
In some GET request, I need to populated numerous fields as I was saying, in particular offers with a sorting by 'price' by ascending.
As the documentation of Mongoose is showing there (http://mongoosejs.com/docs/api.html#query_Query-populate), you can sort by a subpath.
My problem is that it isn't the case.
There is my code which is doing it :
Ads.findOne({ _id: adId })
.populate({ path: 'author', select: 'firstName lastName' })
.populate('images')
.populate({ path: 'offers', options: { sort: { 'price': -1 } })
.populate({ path: 'category', select: 'name' })
.exec(function (err, ad) {
if (err)
deferred.reject({ status: 500, message: 'Database error.' });
else if (!ad)
deferred.reject({ status: 500, message: 'The ad doesn\'t exist!.' });
else {
deferred.resolve(ad.toJSON());
}
})
I have read as much as possible questions/answers giving here or in the Mongoose mailing-list :
I know it's not possible to sort documents results from subdocument result, OK. But I just want to sort that subdocument only, and only this one. Some responses here seems to say it's possible :
I have 2 questions around it :
- Is it possible (as the Mongoose documentation is written) to sort a subdocument during the population ?
- Is it linked to the fact I didn't just put a ObjectId linked to an other Schema ?
Thanks for your answer ;)