Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  188] [ 7]  / answers: 1 / hits: 12965  / 11 Years ago, thu, february 6, 2014, 12:00:00

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}


?


More From » node.js

 Answers
6

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

[#48011] Wednesday, February 5, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisc

Total Points: 533
Total Questions: 82
Total Answers: 90

Location: Bangladesh
Member since Thu, Aug 5, 2021
3 Years ago
ellisc questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Sat, Jun 26, 21, 00:00, 3 Years ago
Mon, Nov 16, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
;