使用MongoDb和Node.js输入数据

Entering data with MongoDb and Node.js

本文关键字:输入 数据 js Node MongoDb 使用      更新时间:2023-09-26

所以我试图将数据输入到节点的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)

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

我认为你最好使用findOne和常规回调:

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

甚至是upsert