【发布时间】:2011-08-29 23:22:53
【问题描述】:
我正在尝试处理不同集合(不是嵌入文档)中的关联文档,虽然 Mongooose 中有一个 issue for that,但我现在正尝试通过延迟加载具有虚拟属性的关联文档来解决它如记录的on the Mongoose website。
问题在于虚拟的getter 将函数作为参数并使用虚拟属性的返回值。当虚拟不需要任何异步调用来计算它的值时,这很好,但是当我需要进行异步调用来加载其他文档时不起作用。这是我正在使用的示例代码:
TransactionSchema.virtual('notebook')
.get( function() { // <-- the return value of this function is used as the property value
Notebook.findById(this.notebookId, function(err, notebook) {
return notebook; // I can't use this value, since the outer function returns before we get to this code
})
// undefined is returned here as the properties value
});
这不起作用,因为函数在异步调用完成之前返回。有没有办法可以使用流控制库来完成这项工作,或者我可以修改第一个函数,以便将 findById 调用传递给 getter 而不是匿名函数?
【问题讨论】:
-
谢谢,我已经更新了代码示例,希望现在更清楚了。
-
我看到 Josh 设法给你异步代码,看。
-
您遇到的问题只是 JS 的“限制”以及 Mongoose 为虚拟同步编写
get方法的方式。它需要一个返回值的函数,并且没有流控制库能够让您将 async 放入其中并使其按预期工作。如果您尝试在 Underscore/lodash 回调中执行异步操作,您将遇到同样的事情。因此需要 Josh 的解决方案来滚动自己的异步方法并绕过 Mongoose 的同步get。
标签: asynchronous node.js mongoose