asynchronous - 如何在 Mongoose 虚拟属性中使用异步代码?

标签 asynchronous node.js mongoose

我正在尝试将不同集合中的文档(不是嵌入文档)关联起来,虽然有 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/

相关文章:

python - Tornado AsyncHTTPClient 获取回调 : Extra parameters?

asynchronous - 如何在 Angular 2 中发出简单的 JSONP 异步请求?

javascript - Node.Js 服务器不断崩溃,但没有错误

javascript - 使用额外字段引用 Mongoose 中的另一个模式

javascript - mongoose:如何循环包含对象引用(_id)的数组

sockets - 如何在 Corona SDK Lua 中运行阻塞操作?

c# - 如何创建 Async ActionResult 以创建用于以下轮询逻辑的 async-await 模式?

json - 如何使用expressJS在Stormpath中获取自定义用户数据?

javascript - (g)rpc 支持动态对象作为参数吗?

javascript - mongodb在文档更新期间使用if else设置字段值