Mik*_*y P 25 asynchronous mongoose node.js
我正在尝试将文档关联到不同的集合(不是嵌入式文档)中,虽然在Mongooose中存在问题,但我现在正试图通过延迟加载具有虚拟属性的关联文档来解决它. Mongoose网站.
问题是虚拟的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
});
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为函数在异步调用完成之前返回.有没有办法可以使用流控制库来完成这项工作,还是可以修改第一个函数,以便将findById调用传递给getter而不是匿名函数?
Jos*_*osh 21
您可以定义一个虚拟方法,您可以为其定义回调.
使用你的例子:
TransactionSchema.method('getNotebook', function(cb) {
Notebook.findById(this.notebookId, function(err, notebook) {
cb(notebook);
})
});
Run Code Online (Sandbox Code Playgroud)
虽然唯一的评论者似乎是那些迂腐类型之一,但您也不应该害怕嵌入文档.它是我所理解的mongos强点之一.
一个人使用上面这样的代码:
instance.getNotebook(function(nootebook){
// hey man, I have my notebook and stuff
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12136 次 |
最近记录: |