Open In App

Mongoose Schema Connection.prototype.set() API

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:

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




// 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




// 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


Article Tags :