Mongoose.js: force always populate
this plugin is a solution to your question:
https://www.npmjs.com/package/mongoose-autopopulate
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');