2013-03-28 34 views
0

所以我試圖用節點將數據輸入到一個mongodb集合中。據我可以告訴我有權訪問該集合。用MongoDb和Node.js輸入數據

var collection = db.collection("whatsGoingOnEvents"); 
if(collection){ 
console.log("hitting stream"); 
var stream = collection.find({time: parsedObject.time, endTime: parsedObject.endTime, lon:parsedObject.lon,lat:parsedObject.lat}).stream(); 
console.log(stream); 
stream.on("data",function(data){ 
    console.log("data"); 
    console.log(data); 
    if(!data){ 
     collection.insert(parsedObject); 
     console.log("hitting insert"); 
    } 
}); 
stream.on("end",function(){ 
//dosomething 
}); 
} 

parsedObject可能會或可能不會有所有這些領域的 - 應該很重要?我認爲如果該字段不存在,那麼collection.find()只是尋找時間來「未定義」,這在技術上仍然是一個值。

我從來沒有擊中console.log("data")所以我從不插入文件。我一直在嘗試關注this link

所以我不知道爲什麼插入沒有發生。我知道,沒有什麼被添加from db.collection.stats();,還告訴我集合的大小爲0

哦也,這是我使用連接到Mongo-什麼

var mongo = require('mongodb').MongoClient; 

EDIT--

我試着回答下面 - 導致這種錯誤 -

lib/mongodb/connection/server.js:481 
     throw err; 
      ^
Error: Cannot use a writeConcern without a provided callback 
    at insertAll (/Users/psanker/Google Drive/Coding/Javascript/WhatsGoingOn/node_modules/mongodb/lib/mongodb/collection.js:332:11) 
    at Collection.insert (/Users/psanker/Google Drive/Coding/Javascript/WhatsGoingOn/node_modules/mongodb/lib/mongodb/collection.js:91:3) 

^因爲我還沒有添加回調到插入上述發生。

回答

1

如果你的查詢不符合任何記錄(這似乎是邏輯的,因爲你寫的集合大小爲0),data事件處理程序將永遠不會被調用(因爲只有當有實際的結果)。

我覺得你用findOne和常規回調更好:

collection.findOne({ params }, function(err, result) { 
    if (err) 
    throw err; 
    if (result === null) { 
    collection.insert(parsedObject, { w: 0 }); 
    } 
}); 

,甚至是upsert

+0

ah - 如果沒有結果返回,是否有事件發生? – praks5432 2013-03-28 10:59:59

+0

也,這是給我一個錯誤 - 錯誤:不能使用writeConcern沒有提供的回調 – praks5432 2013-03-28 11:01:20

+0

我不認爲有'沒有結果'事件,但流只是真正有用的,當你運行查詢可能會返回大量的結果;在這種情況下,結果的最大數量是1. Wrt你的錯誤,請參閱http://stackoverflow.com/a/14410066/893780(我相應地更新了我的答案)。 – robertklep 2013-03-28 11:06:03