Open In App

Mongoose prototype.$set() Method

Last Updated : 27 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Mongoose, the prototype.$set() method is a crucial function that allows developers to update specific fields of a document in a MongoDB collection. This method enables atomic modification of field values within a document, offering precise control over your MongoDB data. This article explains how to use the $set() method effectively in Mongoose with detailed examples.

What is Mongoose prototype.$set() Method?

The prototype.$set() method in Mongoose is used to set the values of specific fields in a MongoDB document. It allows us to modify fields on a document instance and provides a way to interact with individual fields rather than the entire document. The method is flexible and can be used with any model object to assign or modify values for the specified field(s).

  • Field-Specific Updates: Modify specific fields without affecting others.
  • Atomic Updates: Ensures that only the specified fields are updated, maintaining data integrity.
  • Returns the Document: After updating the field(s), it returns the updated document with the latest values.

Syntax:

document.$set( path, value, type, options );

Parameters:

  • path: It is used to specify the path name from the collection for which we want to set new value.
  • value: It is used to provide value to the field.
  • type: It is used to provide data type for the value.
  • options: It is used to assign various properties to the field.

Return Value:

It returns the document object with all the latest values.

How to Use the prototype.$set() Method in Mongoose

The $set() method is highly versatile. Let's walk through practical examples that demonstrate how to use it.

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: Basic Usage - Updating a Single Field

In this example, we have established a database connection using mongoose and defined model over cricketerSchema, having three columns or fields "_id", "name", and "nationality". At the end, we are setting value for name field using $set() method.

Filename: app.js

// Require mongoose module
const mongoose = require("mongoose");

// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const cricketerSchema = new mongoose.Schema({
_id: Number,
name: String,
nationality: String
});

const Cricketer = mongoose.model('Cricketers', cricketerSchema);

(async () => {
const document = await Cricketer.findOne();
document.$set('name', 'Stokes Ben');
document.save().then(result => {
console.log(result)
});
})();

Explanation:

  • $set() is used to modify the name field of the first document in the Cricketers collection.
  • After calling $set(), we save the document, and it returns the updated document with the new name value.

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

node app.js

Output:

{ _id: 1, name: 'Stokes Ben', nationality: 'England', __v: 0 }

GUI Representation of the Database using Robo3T GUI tool:

Example 2: Updating Multiple Fields

In this example, we update both the name and nationality fields for a document in the Cricketers collection.

Filename: app.js

// Require mongoose module
const mongoose = require("mongoose");

// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const cricketerSchema = new mongoose.Schema({
_id: Number,
name: String,
nationality: String
});

const Cricketer =
mongoose.model('Cricketers', cricketerSchema);

Cricketer.find().exec((error, documents) => {
if (error) {
console.log(error);
} else {
let document = documents[1];
console.log('BEFORE SET -', document)
document.$set('name', 'Ishan Kishan');
document.$set('nationality', 'India');
document.save().then(result => {
console.log('AFTER SET -', result);
});
}
});

Explanation:

  • $set() is called twice to update both the name and nationality fields of the second document in the Cricketers collection.
  • After saving the document, we log the changes to verify that both fields were updated.

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

node app.js

Output:

BEFORE SET - { _id: 2, name: 'David Warner', nationality: 'Australia', __v: 0 }
AFTER SET - { _id: 2, name: 'Ishan Kishan', nationality: 'India', __v: 0 }

GUI Representation of the Database using Robo3T GUI tool:

Conclusion

The $set() method in Mongoose is a powerful and flexible way to update specific fields of a document within a MongoDB collection. It allows for precise control over field updates and ensures that only the modified fields are affected. By understanding how to use $set(), we can streamline document manipulation in our Mongoose applications and improve data integrity by keeping updates atomic. Whether we’re updating a single field or multiple fields, $set() simplifies the process and offers a clean, readable approach to modifying documents.


Next Article

Similar Reads