Using new: true In Mongoose
The new: true
option in Mongoose’s findOneAndUpdate
method ensures that the method returns the modified document instead of the original document. This is useful when we want to retrieve the document after it has been updated.
By default, findOneAndUpdate returns the original document before the update operation. However, by using { new: true }, it will instead return the updated document.
Syntax:
Model.findOneAndUpdate(query, update, { new: true });
Example: The below code uses new: true to update the document and fetch the updated document at the time of update.
// importing all requirements
const User = require('../models/User');
// to fetch update the user data
const updateUser = async (req, res) => {
//Find any user and return
const user = await User.findOne({ email: 'gfg@gmail.com' });
// now, we want to update the name of the user
const name = "Geeks For Geeks";
// to get the updated user's data, we have to set the {new: true}
const updatedUser = await User.findOneAndUpdate(
{ email: 'gfg@gmail.com' },
{ $set: { fullName: name }},
{ new: true }
);
// here we will return the user
return res.status(200).json({ oldUser: user, updatedUser });
}
Output:
Explanation: This code snippet defines an asynchronous function updateUser responsible for updating a user’s data in a MongoDB database using Mongoose. Initially, it fetches the user data based on the email address ‘gfg@gmail.com’ using the findOne method. Then, it sets a new name for the user as ‘Geeks For Geeks‘.
Subsequently, it utilizes findOneAndUpdate to update the user’s full name to the new value. By setting the option { new: true }, it ensures that the updated user data is returned. Finally, the function responds with a JSON object containing both the original user data (oldUser) fetched before the update and the updated user data (updatedUser).
How to Use findOneAndUpdate() in Mongoose?
In the world of MongoDB and Node.js development, Mongoose serves as a powerful tool for interacting with MongoDB databases. One of Mongoose’s key methods, findOneAndUpdate, allows developers to easily find a single document in a MongoDB collection, update it, and optionally return either the original or the modified document.
In this article, We will learn about how to Update documents which not returned by Mongoose’s findOneAndUpdate method, through the various methods along with the examples and so on.