Open In App

Mongoose | findOneAndReplace() Function

Last Updated : 19 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with MongoDB in Node.js, Mongoose is an essential tool for schema-based modeling and database operations. One of the most powerful and frequently used functions in Mongoose is findOneAndReplace().

This function helps in finding a document and replacing it with a new one. But how exactly does it work? How can developers use it efficiently to manage data in MongoDB? In this article, we will explain everything about the Mongoose findOneAndReplace() function, including its syntax, usage, and best practices.

What is Mongoose findOneAndReplace()?

The findOneAndReplace() function in Mongoose is used to find a document that matches a certain condition and replace it with the new document provided. This function also returns the original document before it was replaced. It can be extremely useful when you want to update documents while maintaining full control over the operation, including accessing the original document data.

Syntax

Model.findOneAndReplace(filter, replacement, options, callback);

Parameters

  • filter: A query object to find the document (e.g., { age: { $gte: 5 } }).
  • replacement: The new document that will replace the found one.
  • options (optional): Additional options, such as new (returns the new document), upsert (creates a new document if none is found), etc.
  • callback: A callback function that executes after the replacement operation is complete.

Key Features of findOneAndReplace()

1. Find and Replace: This function allows you to search for a document based on specific criteria and replace it with a new document, simplifying the update process.

2. Original Document: It provides access to the original document before the replacement, which can be useful for logging changes or maintaining audit trails.

3. No Partial Updates: Unlike the findOneAndUpdate() function, findOneAndReplace() will replace the entire document, so you need to provide all the fields in the replacement document.

Example of Using findOneAndReplace() in Mongoose

You can visit the link to Install mongoose module. You can install this package by using this command.

npm install mongoose

After installing mongoose module, you can check your mongoose version in command prompt using the command.

npm version mongoose

After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.

node index.js

Filename: index.js

const mongoose = require('mongoose');

// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});

// User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});

var new_user = {
name: "ABC",
age:100
}

// Find document matching the condition(age >= 5)
// and replace first document with above new_user
// This function has 4 parameters i.e. filter,
// replacement, options, callback

User.findOneAndReplace({age: {$gte:5} },
new_user, null, function (err, docs) {
if (err){
console.log(err)
}
else{
console.log("Original Doc : ", docs);
}
});

Explanation:

  • Database Connection: First, we connect to MongoDB using the mongoose.connect() method. Replace 'mongodb://127.0.0.1:27017/geeksforgeeks' with your MongoDB connection string.
  • Defining the Model: A simple schema is created for the User model, which includes two fields: name (a string) and age (a number).
  • Creating a New User Document: A new_user object is created, which will replace the matched document in the database.
  • findOneAndReplace() Operation: The findOneAndReplace() function is called with the filter { age: { $gte: 5 } } to find a document where the age is greater than or equal to 5. If a match is found, it is replaced with new_use

Steps to run the program:

The project structure will look like this: project structure

Make sure you have installed mongoose module using following command:

npm install mongoose

Below is the sample data in the database before the function is executed, We can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Database

Run index.js file using below command:

node index.js

After the function is executed, You can see the database as shown below: new Database

Explanation: So this is how you can use the mongoose findOneAndReplace() function which finds a matching document, replaces it with the provided doc, and passes the returned doc to the callback.

When Should You Use findOneAndReplace()?

While findOneAndReplace() can be a powerful tool, it's essential to know when to use it. Here are some scenarios where it is most useful:

  • Full Document Replacement: When you need to replace the entire document with a new one, not just update specific fields.
  • Data Transformation: If you want to completely transform the structure or content of a document based on specific conditions.
  • Auditing: If you need to access the original document to log changes or maintain an audit trail before replacing it.

Troubleshooting Common Errors

1. Document Not Found Error

If no document matches your filter criteria, findOneAndReplace() will return null. Ensure your filter query is correct and that the document exists in the database.

2. Validation Errors

If you try to replace a document with data that does not satisfy the model's validation rules, Mongoose will throw an error. Make sure your replacement document matches the schema defined for the model.

Conclusion

The Mongoose findOneAndReplace() function is a useful method for developers when working with MongoDB in Node.js. It allows you to find a document, replace it entirely with a new one, and access the original document, making it ideal for full document replacements, auditing, and data transformations. With the examples and guidelines shared in this article, you should be able to incorporate this function into your projects and use it efficiently to manage your MongoDB data.


Next Article

Similar Reads