1

我有一个参考其他文件的模型。我想在该模型中有一个方法可以处理引用模型中使用的数据。

'use strict';

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
    , deepPopulate = require('mongoose-deep-populate');

var MainSchema = new Schema({
  childs: [{type:Schema.ObjectId, ref: 'Child'}], //because many-to-one
  startDate: {type: Date, default: Date.now},
  endDate: {type: Date},
});


MainSchema.methods = {

  retrieveChilds: function(callback) {

    // deepPopulation of childs not possible??

    callback(result);
  },
};

MainSchema.plugin(deepPopulate);

module.exports = mongoose.model('Main', MainSchema);

如上面的代码示例所示,retrieveChilds 函数应在当前 Schema 上执行 deepPopulate 函数。这是可能的还是应该在模型之外发生?(这有时会导致重复的代码)

4

1 回答 1

0

在 Mongoose实例方法中,this是正在调用该方法的文档实例,因此您可以这样做:

MainSchema.methods = {
  retrieveChilds: function(callback) {
    this.deepPopulate('childs.subject.data', callback);
  },
};

然后调用它:

main.retrieveChilds(function(err, _main) {
    // _main is the same doc instance as main and is populated.
});
于 2015-06-16T13:33:56.527 回答