node + mongo:更新记录需要回调

Pir*_*jan 9 javascript mongodb node.js

所以我正在用socket.io监听一个事件,一旦触发我正在尝试将记录更新为新值.

socket.on('contentEdited', function (newContent) {

collection.update(
    { '_id' : ObjectId("5279262e74d92da751eb2b8e") }, 
    { $set: { 
      'content': newContent
      } 
    }
  ), function (err, result) {
    if (err) throw err;
    console.log(result)
  };

});
Run Code Online (Sandbox Code Playgroud)

语法在shell中有效,但在事件触发时会在节点中抛出以下错误:

错误:如果没有提供的回调,则无法使用writeConcern

我尝试在最后添加一个函数用于基本错误检查,但我不确定如何以mongo期望的方式提供回调.

还是有点新鲜,谢谢

the*_*tus 14

我认为你的问题是回调函数需要在更新函数调用内部而不是在它之外.可以在此处找到nodejs MongoDB驱动程序的格式:http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#update

所以看起来应该是这样的:

collection.update(
   { '_id' : ObjectId("5279262e74d92da751eb2b8e") }, 
   { $set: { 'content': newContent } },
   function (err, result) {
      if (err) throw err;
      console.log(result);
   })
Run Code Online (Sandbox Code Playgroud)

请注意,括号在回调函数之后已移动.

您还可以将写入关注设置为"未确认"而不是"已确认".

MongoDB的"写问题"概念决定了MongoDB成功写入数据库的确定程度.最低级别的写入问题,"未确认"只是将数据写入服务器而不等待响应.这曾经是默认值,但现在默认是等待MongoDB确认写入.

您可以在此处了解有关写入问题的更多信息:http: //docs.mongodb.org/manual/core/write-concern/

要将写入问题设置为未确认,请添加以下选项{w: 0}:

collection.update(
   { '_id' : ObjectId("5279262e74d92da751eb2b8e") }, 
   { $set: { 'content': newContent } },
   { w : 0 });
Run Code Online (Sandbox Code Playgroud)