23

私の知る限り、データが入力されたドキュメントを Mongoose で並べ替えることができます ( source )。

入力された 1 つ以上のフィールドでクエリを並べ替える方法を探しています。

次の 2 つの Mongoose スキーマを考えてみましょう。

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
        }]
}]

次のようなものを使用して、それらのウィザードを呪文ダメージで並べ替えたいと思います。

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

私は実際にクエリの後にこれらの並べ替えを手動で行っており、それを最適化したいと考えています。

4

3 に答える 3

11

populate メソッドの必須パラメーターのみを明示的に指定できます。

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

http://mongoosejs.com/docs/api.html#document_Document-populateをご覧ください 。上記のリンクの例を次に示します。

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
})
于 2013-08-30T16:57:38.250 に答える