0

所以我试图将数据输入到带有节点的 mongodb 集合中。据我所知,我可以访问该集合。

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"),所以我从不插入文件。我一直在尝试关注此链接

所以我不确定为什么插入没有发生。我知道没有添加任何内容from db.collection.stats();,这告诉我集合的大小为 0。

哦,这也是我用来连接 Mongo-

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

编辑 -

我尝试了下面的答案 - 导致了这个错误 -

    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)

^发生上述情况是因为我没有向插入添加回调。

4

1 回答 1

1

如果您的查询与任何记录都不匹配(这似乎是合乎逻辑的,因为您编写的集合大小为 0),data则永远不会调用事件处理程序(因为只有在有实际结果时才会调用它)。

我认为你最好使用findOne和定期回调:

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

甚至一个upsert.

于 2013-03-28T10:55:08.830 回答