Open In App

Mongoose Document prototype.replaceOne() API

Last Updated : 27 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The prototype.replaceOne() method of the Mongoose API is used to replace field values of any document present in the collection. We can use replaceOne() on any document object and we will pass the object with field and values as a parameter to the method. It will replace the existing document object with the field and values we provide to the method. This method works the same as the update method but it replaces document values with the existing document values without any atomic operator i.e. $set.

Syntax:

doc.replaceOne()

Parameters: The prototype.replaceOne() method accepts three parameters:

  • doc: It is an object with a field that will replace the existing field.
  • options: It is an object with various properties.
  • callback: It is a callback function that will run once execution is completed.

Return Value: The prototype.replaceOne() function returns a promise. The result contains an object with the following key and values or properties.

// Number of documents matched
res.matchedCount;

// Number of documents modified
res.modifiedCount;

// Boolean indicating everything went smoothly
res.acknowledged;

// null or an id containing a document
// that had to be upserted
res.upsertedId; 

// Number indicating how many documents
// had to be upserted. Will either be 0 or 1
res.upsertedCount;

Setting up Node.js application:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this:

 

Database Structure: The database structure will look like this, the following documents are present in the collection.

 

Example 1: In this example, We have established a database connection using mongoose and defined model over userSchema, having two columns or fields “name”, and “age”. In the end, we are using replaceOne() method on the document object of the User model which will replace the document field and values with the properties we pass as an object to the replaceOne()

  • app.js: Write down the below code in the app.js file:

App.js




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
});
  
// Defining userSchema model
const User = mongoose.model("User", userSchema);
  
const doc = User.findById("63203694182cd3c22ea480ff");
  
doc.replaceOne({ name: "User1 Updated", age: 100 })
.then((output) => {
    console.log(output);
});


Steps to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

{
     acknowledged: true,
     modifiedCount: 1,  
     upsertedId: null,  
     upsertedCount: 0,  
     matchedCount: 1    
}

GUI Representation of the  Database using Robo3T GUI tool:

 

Example-2:  In this example, we are replacing the document object with only one field i.e “name”. We are not providing any value for the “age” field. So, in the database, you will see entire document will be replaced and only the “name” field will have a value, “age” field will have a null o undefined value as we have replaced the entire document with the name field.

  • app.js: Write down the below code in the app.js file:

App.js




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
});
  
// Defining userSchema model
const User = mongoose.model("User", userSchema);
  
const replaceOne = async () => {
  
    // Finding document object using doc _id
    const doc = await User.findById(
        "63204ad5182cd3c22ea486ae"
    );
      
    const output = await doc.replaceOne({ 
        name: "User2 Replaced" 
    })
    console.log(output)
}
replaceOne();


Steps to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

{
      acknowledged: true,
      modifiedCount: 1,  
      upsertedId: null,  
      upsertedCount: 0,  
      matchedCount: 1    
}

GUI Representation of the  Database using Robo3T GUI tool:

 

Reference: https://mongoosejs.com/docs/api/document.html#document_Document-replaceOne



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads