我有一个参考其他文件的模型。我希望在该模型中有一个方法可以处理引用模型中使用的数据。
'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函数。这可能还是应该在模型之外发生? (这有时导致重复的代码)
答案 0 :(得分:0)
在Mongoose instance methods中,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.
});