小编Mik*_*y P的帖子

如何使用Mongoose虚拟属性中的异步代码?

我正在尝试将文档关联到不同的集合(不是嵌入式文档)中,虽然在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而不是匿名函数?

asynchronous mongoose node.js

25
推荐指数
2
解决办法
1万
查看次数

标签 统计

asynchronous ×1

mongoose ×1

node.js ×1