如何在猫鼬虚拟财产异步code工作? [英] How to work with async code in Mongoose virtual properties?

查看:197
本文介绍了如何在猫鼬虚拟财产异步code工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想与关联在不同的集合文件(没有嵌入文档)工作,同时有一个问题为在Mongooose,我想相关的文档解决它现在延迟加载与虚拟财产记录在猫鼬网站

I'm trying to work with associating documents in different collections (not embedded documents) and while there is an issue for that in Mongooose, I'm trying to work around it now by lazy loading the associated document with a virtual property as documented on the Mongoose website.

的问题是,对于一个虚拟吸气需要一个函数作为参数,并使用该虚拟财产的返回值。这是伟大的,当虚拟不需要任何异步调用来计算它的价值,但是当我需要做一个异步调用来加载其他文件不起作用。这里的样本code我的工作:

The problem is that the getter for a virtual takes a function as an argument and uses the return value for the virtual property. This is great when the virtual doesn't require any async calls to calculate it's value, but doesn't work when I need to make an async call to load the other document. Here's the sample code I'm working with:

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调用吸气,而不是一个匿名函数?

This doesn't work since the function returns before the async call is finished. Is there a way I could use a flow control library to make this work, or could I modify the first function so that I pass the findById call to the getter instead of an anonymous function?

推荐答案

您可以定义一个虚拟的方法,你可以定义一个回调。

You can define a virtual method, for which you can define a callback.

使用你的例子:

TransactionSchema.method('getNotebook', function(cb) {
  Notebook.findById(this.notebookId, function(err, notebook) {
    cb(notebook);
  })
});

和而唯一的评论者似乎是那些迂腐的类型之一,你也不要怕嵌入文档。它从我了解的mongos强项之一。

And while the sole commenter appears to be one of those pedantic types, you also should not be afraid of embedding documents. Its one of mongos strong points from what I understand.

One使用上述code,像这样:

One uses the above code like so:

instance.getNotebook(function(nootebook){
    // hey man, I have my notebook and stuff
});

这篇关于如何在猫鼬虚拟财产异步code工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆