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

user8885733
  • 137
  • 2
  • 13
  • 1
    Try `User.findOne({_id: id}).populate({ path:'scores', options: { limit: 10, sort: { createdAt: -1} } })....` – s7vr Jan 04 '18 at 18:11
  • Possible duplicate of [Node js mongoose populate limit](https://stackoverflow.com/questions/32207457/node-js-mongoose-populate-limit) – s7vr Jan 04 '18 at 18:12

1 Answers1

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.

Ezra Chu
  • 832
  • 4
  • 13