0

I have two models User and Score

User model SCHEMA:

var UserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
createdAt: Date,
scores:[
    {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Score"
    }
]
});

My Score model SCHEMA:

var  ScoreSchema =  new mongoose.Schema({
score: Number,
createdAt: Date
});

So, basically I am trying to get all(limit:10) the scores in an sorted order of createdAt field and populating the score array as well.

Query I am using:

User.findOne({_id: id}).populate('scores').sort({createdAt:-1})
 .limit(10).exec(function (err, result) {
    if (err) {
        console.log(err);
        res.json({
            status: 'error',
            data: err
        })
    }
    else {
        res.json({
            status: 'ok',
            data: result
        })
    }
   })

I am still getting all the score and in the unsorted way. Please help

2
  • 1
    Try User.findOne({_id: id}).populate({ path:'scores', options: { limit: 10, sort: { createdAt: -1} } }).... Commented Jan 4, 2018 at 18:11
  • Possible duplicate of Node js mongoose populate limit Commented Jan 4, 2018 at 18:12

1 Answer 1

0

Your sort() and limit() are operating on the User model, not the scores subdocument array. If you want subdocument sorting, you may want to look at this post.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.