Node.js col.insert不';是否发送任何错误,但未插入文档?

Node.js col.insert不';是否发送任何错误,但未插入文档?,node.js,mongodb,Node.js,Mongodb,我经常看到以下代码片段: collection.insert({"some": "data"}, function (err, inserted) { if (err) { /* do something */ return; } if (!inserted || !inserted.length) { console.error("Nothing inserted ..."); return; } /* do something */ });

我经常看到以下代码片段:

collection.insert({"some": "data"}, function (err, inserted) {
   if (err) { /* do something */ return; }
   if (!inserted || !inserted.length) {
       console.error("Nothing inserted ...");
       return;
   }
   /* do something */
});
如果确实需要第二个


insert
方法在回调中不发送
err
并且
inserted
变量为
undefined
null
或类似的内容时?

对于
insert()
回调,我们不需要第二个
if
。但是对于
update()
回调,我们可能需要第二个
if

我认为该代码的作者将
insert()
update()
(?)

插入

旁注:根据文档,我们必须通过{safe:true}才能在
回调
中获得
err参数
,因为它默认为
false
。但我觉得默认情况下对我来说是
真的
(包括生产模式)

更新


传递给
insert
回调的第二个参数可以是
null
(其中
err
也可以是
null
),根据,当您使用MongoDB 2.6(或更高版本)时,写关注点为0,并且传递了回调函数

我没有运行2.6,因此无法亲自测试:

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

MongoClient.connect('mongodb://localhost:27017/demo?w=0', function(err, db) {
  db.collection('test').insert({ foo : 'bar' }, function(err, inserted) {
    console.log('I', inserted);
  });
});

但是,在这种情况下,
inserted
将不是数组,而是纯
null
。因此,检查必须是
if(!inserted){…}
,并且这不会是一个错误(将写关注点设置为0意味着您不想知道插入是否失败)。

阅读文档后,使用node.js进行一些测试,我没有发现第二个if为false的情况,还有其他意见吗?你从哪里看到的?这是不寻常的。嗯,不,由于副本集中的边缘大小写或错误,驱动程序将返回“false”成功。但是,在这种情况下,
inserted
将不是数组,而是纯
null
-我不同意。我得到了这个输出:
I[{foo:'bar',id:52c997cbf228d47261d336ea}]
-所以插入的
是一个数组。是的,如果
inserted
可以
null
那么我们必须检查
如果(!inserted | | |!inserted.length){/*无插入文档*/}
。什么时候插入的
可以是
null
false
未定义的
,或者成功插入后的空数组(no
err
)呢?@IonicăBizău如果你看看我发布的链接,你会注意到
返回回调(null,null)。所以不是数组,而是纯
null
。此外,这应该只发生在MongoDB 2.6上(或者更确切地说是2.5,它最终将作为2.6发布,但仍在开发中)。是的,我可以看到
返回回调(null,null)
,但这是什么时候发生的?当写入关注点设置为0时,第二个参数
null
?@IonicăBizău是什么时候,这意味着您正在告诉MongoDB驱动程序,您不想知道插入是否正常工作或失败。可以这么说,有点火和遗忘模式。@IonicăBizău由于写关注点通常设置在代码中的另一个位置(不在调用insert的位置),这样编写代码可以确保当写关注点变为
0
时,代码不会中断。
collection.update({"some": "data"}, function (err, count) {
    if(err) throw err;

    // SECOND IF        
    if(!count) {
        console.log('NOTHING UPDATED');
    }
});
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/demo?w=0', function(err, db) {
  db.collection('test').insert({ foo : 'bar' }, function(err, inserted) {
    console.log('I', inserted);
  });
});