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}
?
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');
this plugin is a solution to your question:
https://www.npmjs.com/package/mongoose-autopopulate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With