Jessie Emerson
Jessie Emerson

Reputation: 743

findOneAndUpdate return null upon insertion?

What I want is:

  1. return 1 if insertion succeeds even though the document doesn't exist before.
  2. return 1 if update succeeds

But I can't seem to achieve this with findOneAndUpdate which only returns a result if the document exists and is successfully updated.

My query:

User.findOneAndUpdate(
  { email: email },
  { $set: { verified: 1 } },
  { upsert: true }
).exec(callback);

Upvotes: 3

Views: 869

Answers (2)

chridam
chridam

Reputation: 103445

You could access the native driver to call the underlying collection's updateOne() or updateMany() method which will return the full response from Mongo in the updateWriteOpCallback callback as a updateWriteOpResult object that you can use. For example

User.collection.updateOne(
    { "email": email },
    { "$set": { "verified": 1 } },
    { "upsert": true },
    function(err, result) {

        // The number of documents that matched the filter.
        console.log(result.matchedCount); 

        // The number of documents that were modified.    
        console.log(result.modifiedCount);  

        // The number of documents upserted.  
        console.log(result.upsertedCount);   

        // The total count of documents scanned. 
        console.log(result.result.n);     

        // The total count of documents modified.
        console.log(result.result.nModified); 
    }
);

In this case you most probably need to check the result.result.nModified and result.upsertedCount properties to make the above call.

Upvotes: 1

AJ X.
AJ X.

Reputation: 2770

Assuming you want the result to be the updated document, you need to modify your query to look like this:

User.findOneAndUpdate(
  { email: email },
  { $set: { verified: 1 } },
  { upsert: true, returnNewDocument: true }
).exec(callback);

The returnNewDocument property will make the callback return the updated document instead of the original. In the case of an upsert on a non-existing document, it will return the new document instead of an empty set.

Upvotes: 0

Related Questions