Александр
Александр

Reputation: 317

When changing data to Mongodb using the put method, it gives an error

I use method 'PUT' in my code. I send {"name":"newTestName"} in the postman using method 'PUT'. Postman writes : "Internal Server Error" and Console writes error.

Server.js:

app.put("/artists/:id", function(req, res) {
  db.collection("artists").updateOne(      
    { _id: ObjectID(req.params.id) },
    { name: req.body.name },
    function(err, result) {
      if (err) {
        console.log(err);
        return res.sendStatus(500);
      }
      res.sendStatus(200);
    }
  );

Console:

{ MongoError: the update operation document must contain atomic operators.

driver: true,
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {} }

Upvotes: 0

Views: 195

Answers (3)

Sohan
Sohan

Reputation: 6809

Method was changed as a side-effect of introducing the updateOne() method in addition to update() and updateMany() as somewhat of a safeguard to prevent user's from accidentally overriding an entire document.

db.collection("artists").updateOne(
{
  _id: ObjectID(req.params.id) },
  {
   $set: { name: req.body.name } 
  },
);

Or you use replaceOne

db.collection("artists").replaceOne
   (
    { _id: ObjectID(req.params.id) }, { name: req.body.name }
   );

Upvotes: 1

B. Fleming
B. Fleming

Reputation: 7220

The problem is that in an updateOne(filter, update) call, your update portion must contain a valid top-level operator, e.g. $set or $push. Otherwise the entire document will be deleted and replaced with whatever update contains.

Use the $set operator to fix this:

db.collection("artists").updateOne(
    { _id: ObjectID(req.params.id) },
    { $set: { name: req.body.name } },
    ...
);

Upvotes: 1

Muhammad Usman
Muhammad Usman

Reputation: 10148

According to the docs the second argument to updateOne should be update operator expressions like unset, set, rename. The correct query syntax should be

db.collection("artists").updateOne({
        _id: ObjectID(req.params.id)
    }, {
        $set : { name: req.body.name }
    },
    function(err, result) {
        if (err) {
            console.log(err);
            return res.sendStatus(500);
        }
        res.sendStatus(200);
    }
);

Upvotes: 1

Related Questions