JR Galia
JR Galia

Reputation: 17269

Sort Nested document in MongooseJS

This is my schema:

var Review = new Schema({
    user: {type: ObjectId, ref:'User'},
    lastModified: {type: Date, default: Date.now }
});

var Subject = new Schema({
    name: String,
    review: [Review],
    ...
});


The query will return all the subjects with review from a user. 

{'review.user': id} Is it possible to sort the result based on review.lastModified?

Subject.find({'review.user': id}).select('name').sort('???').exec( function(err, subjects){
    if (err) return res.json(error);

    console.log('subject', subjects);
});

Upvotes: 0

Views: 106

Answers (1)

Tyler Brock
Tyler Brock

Reputation: 30136

You cannot sort within a document using MongoDB. Sorting within the document must be done at the application level.

Upvotes: 1

Related Questions