实例方法中的猫鼬种群
Mongoose population in instance methods
我有一个参考其他文档的模型。我希望在该模型中有一个方法可以处理引用模型中使用的数据。
'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 函数。这可能还是应该发生在模型之外? (有时会导致重复代码)
在 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.
});
我有一个参考其他文档的模型。我希望在该模型中有一个方法可以处理引用模型中使用的数据。
'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 函数。这可能还是应该发生在模型之外? (有时会导致重复代码)
在 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.
});