|
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 Javascript
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 Javascript
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 |
Reffered: https://www.geeksforgeeks.org
MongoDB |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |