【问题标题】:Entering data with MongoDb and Node.js使用 MongoDb 和 Node.js 输入数据
【发布时间】:2013-03-28 19:08:25
【问题描述】:

所以我正在尝试使用 node 将数据输入到 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"),所以我从不插入文档。我一直在尝试关注this link

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

^出现上述情况是因为我没有在插入中添加回调。

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

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

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

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

    甚至是upsert

    【讨论】:

    • ah - 如果没有返回结果,是否会发生事件?
    • 另外,这给了我一个错误-错误:如果没有提供回调,就无法使用 writeConcern
    • 我认为没有“无结果”事件,但流仅在您运行可能返回大量结果的查询时才真正有用;在这种情况下,结果的最大数量为 1。Wrt 您的错误,请参阅stackoverflow.com/a/14410066/893780(我相应地更新了我的答案)。
    猜你喜欢
    • 2020-01-02
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 2014-06-19
    • 1970-01-01
    • 2014-11-24
    相关资源
    最近更新 更多