问题描述
据我所知,可以使用Mongoose对填充的文档进行排序()。
我正在寻找一种方法来按一个或多个填充字段对查询进行排序。
考虑这两个Mongoose模式:
var Wizard = new Schema({
name:{type:String}
,spells:{[{type:Schema.ObjectId,ref:'Spell'}]}
});
var Spell = new Schema({
name:{type:String}
,damage:{type:Number}
});
示例JSON:
[{
name:'Gandalf',
spells:[{
name:'Fireball',
damage:20
}]
},{
名称:'Saruman',
法术:[{
名称:'Frozenball',
赔偿金:10
}]
},{
名称:'Radagast',
法术:[{
名称:'Lightball',
赔偿金:15
}]
} ]
我想用他们的法术伤害对这些巫师进行排序,使用类似的东西:
WizardModel
.find({})
.populate('spells',myfields,myconditions,{sort:[ ['damage','asc']]})
//应以正确的顺序返回:Saruman,Radagast,Gandalf
我实际上是在查询后亲自做那些排序,并希望优化它。
问问自己(以下是答案):
我想要什么?
按照法术伤害对巫师进行排序(它应该是一个附加场,可能是法术伤害的总和。
我做了什么:
我已经对向导的SPELLS进行了排序。
你应该怎么做:
Wizard.find({})。sort({power:'asc'})然后填充法术并做任何你喜欢的事情。
力量是巫师中的另一个领域。你将需要它,因为即使你填充你的法术,你将拥有一系列法术并且它对你没有帮助。 / p>
希望这会有所帮助。
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.
Ask yourself(and here are the answers):
What I want?Sort wizards by their spell damage(it should be an aditional field, probably the sum of the spells damage.
What I did:I have sorted the SPELLS of the wizard.
What should you do:Wizard.find({}).sort({ power : 'asc' }) and then populate with spells and do whatever you like.Power is another field in Wizard. You will need it because even if you populate your spells, you will have an array of spells and it won't help you.
Hope this helps.
这篇关于Mongoose,按填充字段排序查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!