Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use findOneAndUpdate in MongoDB in Node

Say previously I had inserted a document into a mongo collection.

    MongoClient.connect(url, function(err,db){
      if(err) {throw err;}
      else {
        document = {action: "alert",
                    protocol: "udp",
                    port: "80",
                    _id: "12" }
        var collection = db.collection("connections");
        collection.insertOne(document, function(err,result){
          if (err) {throw err;}
          else {
            console.log("Successful")
            db.close();
          }
        }
      }

Now I want to update the protocol field. What I have with no luck so far is

     MongoClient.connect(url, function(err,db){
       if (err) { throw err; }
       else {
         var collection = db.collection("connections");
         collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {new: true}, function(err,doc) {
           if (err) { throw err; }
           else { console.log("Updated"); }
         });  
       }
     });

Am I passing the wrong parameters to the findOneAndUpdate method? I connect to the database correctly.

like image 803
Spothedog1 Avatar asked Jun 28 '16 13:06

Spothedog1


2 Answers

=== Aug 2021

Here is an example of using findOneAndUpdate and getting back the updated document:

With the release of v4 of the node.js client, it seems the old solution of returnOriginal: false (which was awful anyway) is no longer the correct answer.

To see the list of available options for the node.js findOneAndUpdate method: https://mongodb.github.io/node-mongodb-native/4.0/interfaces/findoneandupdateoptions.html

But in short, this should work:

const doc = await <Collection>.findOneAndUpdate(
  { ... search },
  {
    $set: {
      field1: 'value 1',
      field2: ['value 2'],
      etc.
    },
  },
  {
    upsert: true,
    returnDocument: 'after', // this is new !
  }
)
like image 73
Zach Smith Avatar answered Sep 23 '22 00:09

Zach Smith


I think you should try

MongoClient.connect(url, function(err,db){
   if (err) { throw err; }
   else {
     var collection = db.collection("connections");
     collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {upsert: true}, function(err,doc) {
       if (err) { throw err; }
       else { console.log("Updated"); }
     });  
   }
 });

If "upsert" set to true, creates a new document when no document matches the query criteria.

like image 24
deleuterio Avatar answered Sep 26 '22 00:09

deleuterio