Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node + mongo: updating a record requires a callback

So I'm listening for an event with socket.io, once that fires I'm trying to update a record to a new value.

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

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

});

The syntax works in the shell, but throws the following error in node when the event fires:

Error: Cannot use a writeConcern without a provided callback

I tried adding an function at the end afterwards for basic error checking, but I'm not sure how to provide a callback in the way mongo expects.

Still kinda new to this, thanks

like image 657
Pirijan Avatar asked Nov 06 '13 04:11

Pirijan


1 Answers

I think your problem is that the callback function needs to be inside the update function call instead of outside it. The format for the nodejs MongoDB driver can be found here: http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#update

So it should look like this:

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

Note that the parentheses has moved after the callback function.

You could also set the write concern to "unacknowledged" instead of "acknowledged."

The MongoDB concept of "Write Concerns" determines how certain you want to be that MongoDB successfully wrote to the DB. The lowest level of write concern, "Unacknowledged" just writes data to the server and doesn't wait to response. This used to be the default, but now the default is to wait for MongoDB to acknowledge the write.

You can learn more about write concerns here: http://docs.mongodb.org/manual/core/write-concern/

To set the write concern to unacknowledged, add the option {w: 0}:

collection.update(
   { '_id' : ObjectId("5279262e74d92da751eb2b8e") }, 
   { $set: { 'content': newContent } },
   { w : 0 });
like image 150
thehiatus Avatar answered Sep 24 '22 04:09

thehiatus