javascript - Mongoose.js: force always populate -
is there way instruct model populate field?
something like, have "field" populated in find query:
{field: schema.objectid, ref: 'ref', populate: true}
?
with mongoose 4.0, can use query hooks in order autopopulate whatever want.
below example introduction document 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 autopopulate:
var autopopulatelead = function(next) { this.populate('lead'); next(); }; bandschema. pre('findone', autopopulatelead). pre('find', autopopulatelead); var band = mongoose.model('band', bandschema, 'bands');
Comments
Post a Comment