【问题标题】:How to use Mongo Collection methods when using Q?使用Q时如何使用Mongo Collection方法?
【发布时间】:2015-10-30 20:25:15
【问题描述】:

我希望在一些代码中更新 Mongo 集合,如下所示:

var Q = Npm.require('q');
var db = new Mongo.Collection('mydb');

function doSomething() {
    var d = Q.defer();
    setTimeout( function() {
        d.resolve();
    }, 1000);
    return d.promise;
}

doSomething().then( function() {
    console.log('before find');
    var records = db.find({}).fetch(); // blocking operation never completes
    console.log('after find');
    console.log(records); // should be []
});

当使用上述代码运行流星时,它会在“找到之前”记录日志,但随后会停止执行,等待db.find 完成。它永远不会完成。

是否有任何解决方案或解决方法?

更新:似乎是 .fetch() 导致了问题。不过我需要这部分,我想处理我从 Mongo 收到的数据。

【问题讨论】:

  • 在流星服务器代码中使用 Promise 并不是真正地道。如果您使用的是导出承诺的 npm 包,请使用以下命令同步提取它们:stackoverflow.com/questions/23773057/a/23777507。否则,您可以尝试将then 回调包装在Meteor.bindEnvironment 中,如.then(Meteor.bindEnvironment(function () {...}))

标签: node.js mongodb meteor promise q


【解决方案1】:

不使用 fetch,而是添加一个回调函数。 它将允许您在检索数据后对其进行操作:

var records = db.find({}, function(error, data){

        // Do something with your data here
});

** 编辑 - 使用上面的回调,返回一个光标。如果要返回包含结果的数组,请使用以下命令:

 var records = db.find({}).toArray(function(error, data){

        // Do something with your data here
});

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 2017-11-02
    • 2015-09-04
    • 2015-04-29
    • 2019-08-21
    • 1970-01-01
    • 2010-10-23
    • 2017-04-26
    • 1970-01-01
    相关资源
    最近更新 更多