Class 11 & 12 ORM - edpuzino/seattle-javascript-401n7 GitHub Wiki
Populate in Middleware
- You can populate in either pre or post hooks. If you want to always populate a certain field, check out the mongoose-autopopulate plugin.
// Always attach populate()
to find()
calls
MySchema.pre('find', function() {
this.populate('user');
});
// Always populate()
after find()
calls. Useful if you want to selectively populate
// based on the docs found.
MySchema.post('find', async function(docs) {
for (let doc of docs) {
if (doc.isPublic) {
await doc.populate('user').execPopulate();
}
}
});
// populate()
after saving. Useful for sending populated data back to the client in an
// update API endpoint
MySchema.post('save', function(doc, next) {
doc.populate('user').execPopulate().then(function() {
next();
});
});