我想创建一个文档,将其保存,然后将其与填充的字段一起返回。这是我的代码,但是填充的字段是不确定的(而不是用户名):
var doc = await new Documents({
authors: [currentUserId, otherUserId]
});
doc.save();
return doc.populate("authors", "name");
(此功能是异步的)。我确定用户ID是正确的,因为稍后再去获得此文档时,一切正常(该文档的作者已正确填充)
Documents.find(/* ... */).populate("authors", "name").exec(/* ... */);
如何在第一个示例中正确填充?
答案 0 :(得分:0)
您需要使用 execPopulate()
函数来填充文档。
doc.populate("authors", "name").execPopulate();
Documents.find(/* ... /).populate("authors", "name").exec(/ ... */);
在这种情况下,您将在 query 上调用 populate 函数,因此 .populate()
可以正常工作。但是
doc.populate("authors", "name");
这里是在文档中调用populate函数,所以这里需要调用execPopulate()
来实际执行populate()
函数。
您可以阅读更多关于此here
此外,您在错误的地方使用了 await
,
var doc = new Documents({
authors: [currentUserId, otherUserId]
});
// await needs to be here
await doc.save();
return doc.populate("authors", "name");