Open In App

Mongoose Document API .prototype.$set() Function

The Mongoose Document API.prototype.$set() method of the Mongoose API is used on the Document model. It allows to set the values for the particular field in the collection. This method we can use on any model object to assign or set the value for fields. Let us understand the set() method using an example.

Syntax:



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

Parameters: This method accepts four parameters as discussed below:

Return Value: It returns the document object with all the latest values.



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 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
    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)
    });
})();

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: In this example, we are illustrating the functionality of $set() method by setting values for name and nationality field.

Filename: app.js




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
    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);
        });
    }
});

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:

 

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


Article Tags :