为什么在 mongoose 中需要 execPopulate 方法来填充现有文档?

问题描述

我知道它的语法和它是如何工作的,但我无法理解它的内部工作原理,为什么一个方法链有时需要另一种方法,而其他时候不需要?

代码工作正常

const cart = await Carts.findById(cartId).populate('product');

但是这段代码没有

let cart = await Carts.findById(cartId);
cart = await cart.populate('product');

为了使其工作,我们使用 execPopulate 方法,其工作方式如下。

let cart = await Carts.findById(cartId);
cart = await cart.populate('product').execPopulate();

现在,就我在 javascript 中阅读方法链而言,如果没有 execPopulate 方法代码也应该可以正常运行。但我似乎无法理解为什么 populate 对现有的猫鼬对象不起作用。

解决方法

您在两种不同类型的对象上使用 populate() 方法 - 即 querydocument - 它们有自己的方法规范。

https://mongoosejs.com/docs/api/query.html#query_Query-populate https://mongoosejs.com/docs/api/document.html#document_Document-populate

,

Carts.findById(cartId); 返回查询对象。

当您使用 await Carts.findById(cartId); 时,它会返回文档,因为它将解析承诺并获取结果。

await 运算符用于等待 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

有效案例

const cartQuery = Carts.findById(cartId);
const cart = await cartQuery.populate('product');

.execPopulate 是用于文档的方法,而 .populate 用于查询对象。