Chris
Chris

Reputation: 1304

Value not updating in MongoDB

I am trying to update a value from a model by passing to request body value. But sometimes it's updating and sometimes not updating.

Can anyone tell me where I am going wrong? PUT is my method.

Code

TS

accept = (req, res) => {
    this._model.update({
        person1: new mongoose.Types.ObjectId(req.body.person1),
        person2: new mongoose.Types.ObjectId(req.body.person2)
    }, {
        $set: {
            status: "active"
        }
    }, (err, data) => {
        if (err) {
           res.send(err);
        } else {
            res.send(data);
        }
    });
}

Model

{
   "_id":"5d2715cea9ae086ac295c6d8",
   "status":"pending",
   "person1":ObjectId("5cfe4dd898fd225ef1c99ded"),
   "person2":ObjectId("5d02197e2859122fa28c189b")
}

Request

{
    "person1": "5cfe4dd898fd225ef1c99ded",
    "person2": "5d02197e2859122fa28c189b"
}

Response

  {    "ok": 0,
       "n": 0,
      "nModified": 0
   }

Upvotes: 1

Views: 1157

Answers (2)

krbalaji
krbalaji

Reputation: 474

I am using async/await. you can do it also using callback

let ObjectId = require('mongoose').Types.ObjectId
accept = async (req, res) => {
    try {
        const data = await  this._model.update({
            person1: new ObjectId(req.body.person1),
            person2: new ObjectId(req.body.person2)
        }, {
            $set: {
                status: "active"
            }
        })
        if(data.nModified == 1 && data.ok == 1) {
            return res.send(data);
        }
        return res.send("not updated");
    } catch (err) {
        res.send(err)
    }
}

Upvotes: 1

Mohammed Salah
Mohammed Salah

Reputation: 144

Make sure that the person1 and person2 saved as Object Id try

accept = (req, res) => {
    this._model.update({
        person1: req.body.person1,
        person2: req.body.person2
    }, {
        $set: {
            status: "active"
        }
    }, (err, data) => {
        if (err) {
           res.send(err);
        } else {
            res.send(data);
        }
    });
}

Upvotes: 0

Related Questions