0 votes
1 view
in Web Technology by (42.1k points)

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.

1 Answer

0 votes
by (90.8k points)

You can try the following code:

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"); }

     });  

   }

 });

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...