Javascript 使用MongoDb和Node.js输入数据

Javascript 使用MongoDb和Node.js输入数据,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,因此,我尝试将数据输入到带有节点的mongodb集合中。据我所知,我可以接触到这些藏品 var collection = db.collection("whatsGoingOnEvents"); if(collection){ console.log("hitting stream"); var stream = collection.find({time: parsedObject.time, endTime: parsedObject.endTime, lon:parsedObject.lo

因此,我尝试将数据输入到带有节点的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(“数据”),所以我从未插入文档。我一直在努力跟上

所以我不知道为什么插入没有发生。我知道没有从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)

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

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

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


或者甚至是一个。

ah-如果没有返回结果,是否会发生一个事件?另外,这给了我一个错误-错误:如果没有提供的回调,就不能使用writeConcern我不认为会有“无结果”事件,但流只在运行可能返回大量结果的查询时才真正有用;在这种情况下,最大结果数为1。请更正错误,请参阅(我相应地更新了答案)。
collection.findOne({ params }, function(err, result) {
  if (err)
    throw err;
  if (result === null) {
    collection.insert(parsedObject, { w: 0 });
  }
});