How do I update/upsert a document in Mongoose?
Upsert a document with Mongoose using the findOneAndUpdate()
method paired with the { upsert: true }
option. This command either updates an existing document if a match exists, or inserts a new one if there's no match:
Use {new: true}
for immediate results
Including { new: true }
in your operation is important. This returns the modified document rather than the original. Without this, you’ll get back the old document, while your database will quietly keep the updated one a secret. We definitely don’t want that, do we?
Keep track of time with createdAt
and updatedAt
By enabling timestamps in your schema, Mongoose will automatic track and update createdAt
and updatedAt
timestamps for us:
Imagine the power of time travel right within your database! 🔮
Targeted field updates using update()
What if you want to surgically alter a specific field without bothering the others? In such delicate operations, Model.update()
paired with { upsert: true }
is your scalpel:
Avoid _id
duplicates during upsert
Beware of unexpected duplicate _id
errors during upserts. A simple trick to avoid this headache is to remove the _id
field before upserting:
The slow and steady findOne
+ save()
If you're using middleware or hooks not triggered by findOneAndUpdate
, you could opt for the traditional findOne
method followed by save()
:
Warning! Alert! Alert! This method doubles your database calls. Handle with care. 🚨
Quiet the findOneAndUpdate
deprecation warnings
Wave goodbye to findOneAndUpdate
deprecation warnings by using { useFindAndModify: false }
:
Goodbye, pesky warnings! 🥳
Use Model.updateOne()
for unique cases
For updates with unique properties, Model.updateOne()
is your best buddy:
Call for Model.upsert()
?
We could use a Model.upsert()
function to simplify upsert operations, don't you agree? What a gamechanger that would be!
Guides for further study
Take a dive into detailed tutorials and read the Mongoose documentation to broaden your understanding and level-up your efficiency with upserts.
Was this article helpful?