我正在尝试将不同集合中的文档(不是嵌入式文档)关联起来,虽然在 Mongooose 中存在问题,但我现在正试图通过延迟加载具有虚拟属性的关联文档来解决它,如记录在猫鼬网站。
问题是虚拟的 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 而不是匿名函数?