Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb Node.js Driver - findOneAndUpdate() behavior without a field given

I noticed a strange behavior with the mongodb node.js driver findOneAndUpate()...

I mistakenly gave it just a objectId string....thinking it would default to searching by _id field of a document.... so, when I used

User.prototype.updatePetArray = function(user, petElement) {
  return this.collection.findOneAndUpdate(user,
    { $push: { pets:  petElement } },
    { returnOriginal: false,
      maxTimeMS: QUERY_TIME});
}

it pulled up and modified this document, which does not have this number at all:

{ "_id" : ObjectId("56d4e2a381c9c28b3056f792"), "username" : "bob123", "location" : "AT", ...}

Why did it modify this document when 56d4d35881c9c28b3056f78a is not in the document?

like image 987
dman Avatar asked Jun 29 '26 19:06

dman


1 Answers

After I test it following your code with one non-exist ObjectID,

  var col = db.collection('users');
  col.findOneAndUpdate('56cd129222222', {fname: 'Daved'}, function(err, r) {
    if (err)
        console.log(err);
    else
        console.log(r);
    db.close();
  });

As a result the first document in the collection was changed .

Per this doc

findOneAndUpdate(filter, update, options, callback)

filter: Specify an empty document { } to update the first document returned in the collection.

So I think this non-exist ObjectId is consider to the same behavior with {}


After reviewing the source code of findAndModify, eventually, the

  // Execute the command
  self.s.db.command(queryObject

is invoked, and the queryObject is

var queryObject = {
     'findandmodify': self.s.name
   , 'query': query
  };

So I test runCommand in mongo shell with non-exist ObjectId as below, as result, the first document is returned.

> db.users.runCommand({findandmodify: 'users', query: '123ddae344', update: true
})
{
        "lastErrorObject" : {
                "updatedExisting" : true,
                "n" : 1
        },
        "value" : {
                "_id" : ObjectId("56c687275d81735019263d1f"),
                "fname" : "Daved"
        },
        "ok" : 1
}
like image 112
zangw Avatar answered Jul 01 '26 11:07

zangw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!