Reputation: 303
Can I do .populate()
on instance of mongoose model that I already did .find()
?
So this is the school example:
Model.findById(id).populate("bar").exec(function(err, document){
doSth(document);
});
But I would like to do my .find()
separately in middleware, and pass the result if needed to block that will .populate()
it. Sth like this:
var foo;
Model.findById(id, function(err, document){
foo = document;
});
foo.populate("bar");
doSth(foo);
or:
foo.populate("bar").exec(function(err, document){
doSth(document);
});
Is it possible?
Upvotes: 1
Views: 127
Reputation: 36
There are indeed multiple ways: https://mongoosejs.com/docs/api.html#document_Document-populate
It's important if you're using async/await, to not forget to add .execPopulate()
, like:
let foo = await Foo.findOne({}).exec()
await foo.populate('bar').execPopulate()
Upvotes: 0
Reputation: 2134
Yes, you can do this
foo.populate('bar', function(err) {
console.log(foo.bar);
});
I found this solution here. Let me know if it helps you.
Upvotes: 1