Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose.js: force always populate

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} 

?

like image 791
WHITECOLOR Avatar asked Feb 06 '14 01:02

WHITECOLOR


2 Answers

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'); 
like image 113
Mustafa Dokumacı Avatar answered Sep 17 '22 15:09

Mustafa Dokumacı


this plugin is a solution to your question:

https://www.npmjs.com/package/mongoose-autopopulate

like image 25
Reto Avatar answered Sep 18 '22 15:09

Reto