What is the actual difference between findOneAndUpdate and findOneAndReplace

4,823 views
Skip to first unread message

Rafał Ruciński

unread,
Oct 13, 2015, 2:12:27 PM10/13/15
to node-mongodb-native
Hello,

I've recently installed the newest version of node-mongodb-native, 2.0.45.
I've been looking for the findAndModify method that I've been using before and found out it got deprecated in the meantime, and is now replaced by findOneAndUpdate and findOneAndReplace.
As I was wondering how did findOneAndReplace come about, I looked into the source code and found out that both of the new methods are almost identical.

To be extra sure, I've performed a test:

var _id;

Post.insertOne({ a: 1 })
 
.then((result) => {
    _id
= result.insertedId;


   
return Post.find({ _id }).limit(1).next();
 
})
 
.then((result) => {
    console
.log(result);


   
return Post.findOneAndUpdate({ _id }, { $set: { b: 1 } }, { returnOriginal: false });
 
})
 
.then((result) => {
    console
.log(result);


   
return Post.findOneAndReplace({ _id }, { $set: { c: 1 } }, { returnOriginal: false });
 
})
 
.then((result) => {
    console
.log(result);
 
});

and the result was:

{ _id: 561d483c5e0f7e684c1f88d8, a: 1 }

{ value: { _id: 561d483c5e0f7e684c1f88d8, a: 1, b: 1 },
  lastErrorObject: { updatedExisting: true, n: 1 },
  ok: 1 }

{ value: { _id: 561d483c5e0f7e684c1f88d8, a: 1, b: 1, c: 1 },
  lastErrorObject: { updatedExisting: true, n: 1 },
  ok: 1 }

The docs for findOneAndReplace suggest that the last object should look more like this:

{ _id: 561d483c5e0f7e684c1f88d8, c: 1 }

So what's the deal with this method? Why does it do the same as findOneAndUpdate?

Rafał Ruciński

unread,
Oct 29, 2015, 8:06:09 AM10/29/15
to node-mong...@googlegroups.com
Can someone please answer? :(

--
You received this message because you are subscribed to the Google Groups "node-mongodb-native" group.
To unsubscribe from this group and stop receiving emails from it, send an email to node-mongodb-na...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Christian Kvalheim

unread,
Oct 29, 2015, 8:11:43 AM10/29/15
to node-mongodb-native
In practice nothing it's just a convenience method.

The values returned are due to this API being implemented before they revised the current crud specification. Always look at the actual driver API not the crud spec.


Changing this will not be possible until at least 3.0.0

results are always

Name Type Description
value object

Document returned from findAndModify command.

lastErrorObject object

The raw lastErrorObject returned from the command.

ok Number

Is 1 if the command executed correctly.

To unsubscribe from this group and stop receiving emails from it, send an email to node-mongodb-native+unsub...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages