Mongoose.js: force always populate

javascript, mongodb, mongoose, node.js

Solution

With Mongoose 4.0, you can use Query Hooks in order to autopopulate whatever you want.

Below example is from introduction document by Valeri Karpov.

Definition of Schemas:

var personSchema = new mongoose.Schema({
  name: String
});

var bandSchema = new mongoose.Schema({
  name: String,
  lead: { type: mongoose.Schema.Types.ObjectId, ref: 'person' }
});

var Person = mongoose.model('person', personSchema, 'people');
var Band = mongoose.model('band', bandSchema, 'bands');

var axl = new Person({ name: 'Axl Rose' });
var gnr = new Band({ name: "Guns N' Roses", lead: axl._id });

Query Hook to autopopulate:

var autoPopulateLead = function(next) {
  this.populate('lead');
  next();
};

bandSchema.
  pre('findOne', autoPopulateLead).
  pre('find', autoPopulateLead);

var Band = mongoose.model('band', bandSchema, 'bands');

Problem

Is there a way to instruct model to populate ALWAYS a certain field? Something like, to have "field" populated in any find query: ``` {field: Schema.ObjectId, ref: 'Ref', populate: true} ``` ?

Original source