Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k 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 (108k points)
edited by

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

     });  

   }

 });

If you want to learn full-stack web development in detail, this Full Stack Developer Course is the perfect fit for you. 

Related questions

0 votes
1 answer
asked Mar 15, 2020 by ashely (50.2k points)
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
2 answers

Browse Categories

...