Mongoose population in instance methods

1.2k Views Asked by At

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)

1

There are 1 best solutions below

1
On BEST ANSWER

In Mongoose instance methods, this is the document instance the method is being called on, so you can do this as:

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

Then to call it:

main.retrieveChilds(function(err, _main) {
    // _main is the same doc instance as main and is populated.
});