且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mongoose,按填充字段排序查询

更新时间:2023-01-30 13:27:53

问问自己(以下是答案):



我想要什么?
按照法术伤害对巫师进行排序(它应该是一个附加场,可能是法术伤害的总和。



我做了什么:
我已经对向导的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.