Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As far as I know, it's possible to sort populated docs with Mongoose (source).

I'm searching for a way to sort a query by one or more populated fields.

Consider this two Mongoose schemas :

var Wizard = new Schema({
    name  : { type: String }
, spells  : { [{ type: Schema.ObjectId, ref: 'Spell' }] }
});

var Spell = new Schema({
    name    : { type: String }
,   damages : { type: Number }
});

Sample JSON:

[{
    name: 'Gandalf',
    spells: [{
            name: 'Fireball',
            damages: 20
        }]
}, {
    name: 'Saruman',
    spells: [{
            name: 'Frozenball',
            damages: 10
        }]
}, {
    name: 'Radagast',
    spells: [{
            name: 'Lightball',
            damages: 15
        }]
}]

I would like to sort those wizards by their spell damages, using something like :

WizardModel
  .find({})
  .populate('spells', myfields, myconditions, { sort: [['damages', 'asc']] })
// Should return in the right order: Saruman, Radagast, Gandalf

I'm actually doing those sorts by hands after querying and would like to optimize that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
817 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can explicitly specify only required parameters of populate method:

WizardModel
  .find({})
  .populate({path: 'spells', options: { sort: [['damages', 'asc']] }})

Have a look at http://mongoosejs.com/docs/api.html#document_Document-populate Here is an example from a link above.

doc
.populate('company')
.populate({
  path: 'notes',
  match: /airline/,
  select: 'text',
  model: 'modelName'
  options: opts
}, function (err, user) {
  assert(doc._id == user._id) // the document itself is passed
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...