The updateOne function is not working, returns me OK, but does not change anything

Asked

Viewed 64 times

1

I am using Mongodb to do data persistence in my application, with Nodejs.

I make the call like this:

module.exports = function (app) {
    var dbConfig = app.config.db;

    return {
        changeAccountStatus: function (request, response, next, obj) {
            dbConfig.mongoclient.connect(dbConfig.mongourl, function(err, db) {
                if (err) {
                    console.log(err);
                    db.close();
                }
                else{
                    var dbo = db.db(dbConfig.mongodbname);
                    dbo.collection("driver").updateOne({_id: obj._id}, {$set: {accountstatus: obj.accountstatus}}, function(err, result) {
                        //Código do handler
                    });
                    db.close();
                }
            });
        }
    }
}

Sending a JSON via POST:

{
    "_id":"5a7234ee869cd6058834acae",
    "accountstatus":"active"
}

The field $filter of updateOne would be: { _id: '5a7234ee869cd6058834acae' }

And the $update: { '$set': { accountstatus: 'active' } }

In my view, the code is all right; send an existing ID along with the new accountStatus I want to change. But I always get the message.

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

That nothing’s changed. I don’t know what I’m doing wrong.

1 answer

2


He may not be finding the document due to searching for _id be objectid, then you can do the following:

const {ObjectId} = require('mongodb');
[...]
updateOne({_id: new ObjectId(obj._id)}
  • I figured it could be something like this, in other places I read about it said I could only use the string, but I’ll test anyway, since I’m not getting anywhere.

  • OK, when you finish, come back here and tell me if it worked =]

  • 1

    In fact it worked, but only one addendum in his answer, the function ObjectId() does not need the new, to use directly after giving var mongodb = require('mongodb') thus: mongodb.ObjectId(obj._id)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.