Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS MongoDB - how to fix update operation document must contain atomic operators?

I'm new to mongodb and Nodejs, I want to know what is the problem with my code,

I'm encountering update operation document must contain atomic operators when using updateOne,

here is my code,

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://url-this-is-working";


MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbase = db.db("SampleNodeDB"); 
  var myquery = { address: "Valley 345" };
  var newvalues = { name: "Mickey", address: "Canyon 123" };
  dbase.collection("customers").updateOne(myquery, newvalues, function(err, res) {
    if (err) throw erre
    console.log("1 document updated");
    db.close();
  });
});

can someone help me identify and correct the problem,

thankyou!

like image 397
apelidoko Avatar asked Jan 05 '18 07:01

apelidoko


People also ask

Is updateOne Atomic?

updateOne() A write operation on a single document in MongoDB is atomic. When fields must be updated at the same time, embedding them within the same document ensures that the fields can be updated atomically.

What is atomic operation in MongoDB?

In MongoDB, a write operation is atomic on the level of a single document, even if the operation modifies multiple embedded documents within a single document.


2 Answers

The updateOne() method has the following form.

db.collection.updateOne(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

Example

try {
   db.restaurant.updateOne(
      { "name" : "Pizza Rat's Pizzaria" },
      { $set: {"_id" : 4, "violations" : 7, "borough" : "Manhattan" } },
      { upsert: true }
   );
} catch (e) {
   print(e);
}
like image 182
Saniya syed qureshi Avatar answered Sep 23 '22 16:09

Saniya syed qureshi


You try to update to new values with the query

    var newvalues = { name: "Mickey", address: "Canyon 123" };

but you should add $set operator, which is an atomic operator like $inc, $push etc., to make it an update query. Like this;

    var newvalues = { $set: {name: "Mickey", address: "Canyon 123"} };
like image 35
angrylemon Avatar answered Sep 19 '22 16:09

angrylemon