我正在尝试将不同集合中的文档(不是嵌入文档)关联起来,虽然有 issue for that在 Mongooose 中,我现在正在尝试通过延迟加载具有虚拟属性的关联文档来解决它,如文档中所述 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 而不是匿名函数?
最佳答案
你可以定义一个虚方法,你可以为它定义一个回调。
使用您的示例:
TransactionSchema.method('getNotebook', function(cb) {
Notebook.findById(this.notebookId, function(err, notebook) {
cb(notebook);
})
});
虽然唯一的评论者似乎是那些迂腐的类型之一,但您也不应该害怕嵌入文档。据我了解,这是 mongos 的强项之一。
这样使用上面的代码:
instance.getNotebook(function(nootebook){
// hey man, I have my notebook and stuff
});
关于asynchronous - 如何在 Mongoose 虚拟属性中使用异步代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6077601/