I have a model with reference to other documents. I would like to have a method in that model that can process data used in the referenced models.
'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);
as seen in the code example above, the retrieveChilds function should execute a deepPopulate function on the current Schema. Is this possible or should it happen outside the model? (Which results in duplicate code sometimes)
In Mongoose instance methods,
this
is the document instance the method is being called on, so you can do this as:Then to call it: