MichaelLearner
MichaelLearner

Reputation: 469

Usage of execPopulate()

I got stuck with using execPopulate. I've read the documentation, but I don't still get it.

When should I use execPopulate() after populate() and when not?

Here I can't and don't have to use it:

  const courses = await Course.find().populate("userId")

But here I must:

const user = await User.findById("323223ad");
const user = await user
.populate('cart.items.courseId')
.execPopulate()

Upvotes: 0

Views: 2181

Answers (1)

Pipe
Pipe

Reputation: 2424

The first one:

const courses = await Course.find().populate("userId")

operates over the model class... it finds and populate those fields. No execPopulateNeeded.

The second one:

const user = await User.findById("323223ad");
const user = await user
.populate('cart.items.courseId')
.execPopulate()

Operates over an instance of a class (over a MongoDB record instance).

You need to specify when to execute the populate()... you can chain many populate()s.

Upvotes: 1

Related Questions