I know the syntax of it and how it works, but I cannot understand the internal workings, why does a method chaining require another method at one time, but doesn't some other time?
This code works fine
const cart = await Carts.findById(cartId).populate('product');
But this code does not
let cart = await Carts.findById(cartId);
cart = await cart.populate('product');
And to make it work, we use the execPopulate
method which works like this.
let cart = await Carts.findById(cartId);
cart = await cart.populate('product').execPopulate();
Now, as far as I have read method chaining in javascript, the code should run fine without the execPopulate
method too. But I cannot seem to understand why populate does not work on existing mongoose objects.
Carts.findById(cartId);
returns query Object.
When you use await Carts.findById(cartId);
it returns the document as it will resolve the promise and fetch the result.
The await operator is used to wait for a Promise.
let cart = await Carts.findById(cartId); // cart document fetched by query
cart = await cart.populate('product'); // you can't run populate method on document
Valid case
const cartQuery = Carts.findById(cartId);
const cart = await cartQuery.populate('product');
.execPopulate is method on document, while .populate works on query object.