【问题标题】:node.js and mongodb-native: wait till a collection is non-emptynode.js 和 mongodb-native:等到集合非空
【发布时间】:2013-02-06 19:41:55
【问题描述】:

我正在使用 node.js 和本机 mongodb 驱动程序 (node-mongodb-native);

我当前的项目使用 node.js + now.js + mongo-db。

系统基本上是从浏览器向node.js发送数据,用haskell处理后再次反馈给浏览器。

通过表单和 node.js 将文本插入到名为“messages”的 mongo-db 集合中。 haskell 线程读取条目并将结果存储在 db 集合“结果”中。这很好用。

但现在我需要等待结果出现在集合结果中的 javascript 代码。

伪代码:

   wait until the collection result is non-empty.
   findOne() from the collection results.
   delete the collection results.

我目前像这样连接到 mongodb:

    var mongo = require('mongodb'),
    Server = mongo.Server,
    Db = mongo.Db;

    var server = new Server('localhost', 27017, {
        auto_reconnect: true
    });
    var db = new Db('test', server);

我的haskell 知识很好,但不是我的javascript 技能。 所以我进行了广泛的搜索,但没有走多远。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    很高兴你解决了它,我打算写一些类似的东西:

    setTimeout(function(){ 
       db.collection('results',function(coll){
          coll.findOne({}, function(err, one){
            if( err ) return callback(err);
            coll.drop(callback); //or destroy, not really sure <-- this will drop the whole collection
          });
       });
    } ,1000);
    

    【讨论】:

    • 嘿,谢谢你的回答。我以为我自己找不到解决方案,所以你的回答对我来说是安全的。 (我只是在一个开源项目的实施者会议上,所以我们必须快速编码......)。
    【解决方案2】:

    解决方案是使用async 库。

    var async = require('async');
    globalCount = -1;
    
    async.whilst(
        function () {
            return globalCount<1;
        },
        function (callback) {
    
            console.log("inner while loop");
            setTimeout(db_count(callback), 1000);
        },
        function (err) {
            console.log(" || whilst loop finished!!");
        }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 2020-04-01
      • 2012-03-08
      • 2019-11-25
      • 2016-06-10
      • 2013-08-31
      • 2011-07-23
      相关资源
      最近更新 更多