【问题标题】:Get error node.js mongodb cannot read property 0 of null for records after successfull insert成功插入后获取错误 node.js mongodb cannot read property 0 of null for records
【发布时间】:2014-09-11 11:22:37
【问题描述】:

我使用 db.collection.insert 方法在 mongodb 中添加一个带有 function(err,records) 回调的文档。虽然插入成功(我在 mongolab 上检查了记录),但 records 为 null,因此它在 records[0]._id

处引发错误

这是我正在测试的 nitrous.io 上的 node.js 错误吗?

MongoClient.connect(uri, function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");

        // Insert document in MongoDb Collection
                var document = {title:'test',category:'node.js'}

                db.collection('tut').insert(document, function(err,records){
                        //if (err) throw err;
                        console.log('inserted record id: ' + records[0]._id);
                  });
    }
    db.close();
});

【问题讨论】:

  • 您能否编辑您的问题以包含您所描述的代码?
  • @JohnnyHK 我刚刚更新了
  • 刚刚意识到这就像我第四次遇到同样的问题......你赢得了投票:)

标签: node.js nitrousio


【解决方案1】:

您将在 insert 调用完成之前关闭连接。在回调中移动您的 db.close(); 调用:

MongoClient.connect(uri, function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");

        // Insert document in MongoDb Collection
        var document = {title:'test',category:'node.js'}

        db.collection('tut').insert(document, function(err,records){
            //if (err) throw err;
            console.log('inserted record id: ' + records[0]._id);
            db.close();
        });
    }
});

请记住,您不应频繁打开和关闭MongoClient 连接池。通常最好在启动时将其打开并保持打开状态,直到您的应用关闭。

【讨论】:

    猜你喜欢
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2018-01-23
    相关资源
    最近更新 更多