Mongoose,按填充字段对查询进行排序 [英] Mongoose, sort query by populated field
问题描述
据我所知,可以使用 Mongoose (来源).
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.
考虑这两个猫鼬模式:
var Wizard = new Schema({
name : { type: String }
, spells : { [{ type: Schema.ObjectId, ref: 'Spell' }] }
});
var Spell = new Schema({
name : { type: String }
, damages : { type: Number }
});
示例 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.
推荐答案
你可以只明确指定 populate 方法所需的参数:
You can explicitly specify only required parameters of populate method:
WizardModel
.find({})
.populate({path: 'spells', options: { sort: [['damages', 'asc']] }})
看看 http://mongoosejs.com/docs/api.html#document_Document-populate这是上面链接中的一个示例.
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
})
这篇关于Mongoose,按填充字段对查询进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!