Denis B
Denis B

Reputation: 303

populating instance of mongoose model

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

Answers (2)

chab42
chab42

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

PaulShovan
PaulShovan

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

Related Questions