2012-02-24 132 views
0

我使用node.js和本地mongodb驅動程序(node-mongodb-native);node.js和mongodb-native:等到一個集合非空

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

該系統基本上將瀏覽器中的數據發送到node.js,後者使用haskell進行處理,然後再次反饋給瀏覽器。

通過窗體和node.js文本插入到名爲「messages」的mongo-db集合中。 haskell線程讀取條目並將結果存儲在db集合「results」中。這工作正常。

但現在我需要等待結果出現在收集結果中的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技能。 所以我做了大量的搜索,但是我沒有走得太遠。

回答

2

高興你解決它,我會寫類似的東西:

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); 
+0

嘿,感謝你回答。我以爲我自己找不到解決方案,所以你的答案可以保護我。 (我只是在一個開源項目的實現者會議上,所以我們必須快速編寫代碼...)。 – mrsteve 2012-02-25 01:47:37

+0

歡迎您。 – mindandmedia 2012-02-25 10:02:22

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!!"); 
    } 
); 
相關問題