Open In App

Mongoose Schema Connection.prototype.set() API

Last Updated : 14 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Connection.prototype.set() method of the Mongoose API is used on the Connection object. It allows us to set the value for keys in the options object. We can provide the key and its value to the set() method in order to set the options for the connection object. Let us understand the set() method using an example.

Syntax:

connection.set( <key>, <value> );

Parameters: This method accepts two parameters as described below:

  • key: It is used to specify the name of the key in the object.
  • value: It is used to specify the value for the key in the object.

Return Value: This method does not return any value.

Setting up Node.js Mongoose 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:

 

Example 1: The below example illustrates the basic functionality of the Mongoose Connection set() method. We are setting the key as connectionName and the value as connectionObject.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
connectionObject.set("connectionName", "connectionObject");
  
console.log(connectionObject.options.connectionName);


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

node app.js

Output:

connectionObject

Example 2: The below example illustrates the basic functionality of the Mongoose Connection set() method. We are setting key as databaseName and value as geeksforgeeks.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
connectionObject.set("databaseName", "geeksforgeeks");
  
const { databaseName } = connectionObject.options
  
console.log(databaseName);


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

node app.js

Output:

geeksforgeeks

Reference: https://mongoosejs.com/docs/api/connection.html#connection_Connection-set



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads