WHITECOLOR
WHITECOLOR

Reputation: 26170

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}

?

Upvotes: 31

Views: 14431

Answers (3)

pelcomppl
pelcomppl

Reputation: 575

I use query hook to autopopulate, but it not works with create() and save() for modified fields. This is my code:

var autoPopulate = function(next) {
  this.populate('updated_by','name').populate('created_by','name');
  next();
};

ProjectSchema.pre('findOne', autoPopulate);
ProjectSchema.pre('find', autoPopulate);

If I update Project only created_by is populated

If I create new Project both created_by and updated_by are not populated.

find and findOne works with no problems.

What should I do to always populate both: created_by and updated_by?

Upvotes: 0

Mustafa Dokumacı
Mustafa Dokumacı

Reputation: 3015

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');

Upvotes: 48

Reto
Reto

Reputation: 3141

this plugin is a solution to your question:

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

Upvotes: 4

Related Questions