Open In App

Mongoose Connection.prototype.get() Function

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

The Mongoose Schema API Connection.prototype.get() method of the Mongoose API is used on the Connection object. It allows us to get the value of the option properties. Using this method we can fetch the values of different properties from options object. Let us understand get() method using an example.

Syntax:

connectionObject.get( key );

Parameters: This method accepts a single parameter as described below:

  • key: It is used to specify the name of the key or property in the options object.

Return Value: This method returns value in the string form.

Setting up Node.js Mongoose Module:

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 get() method. We are accessing value of dbName property that we configured on connection object.

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('dbName', 'geeksforgeeks');
  
// Fetching property value using get() method
console.log(connectionObject.get('dbName'));


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

Example 2: The below example illustrates the basic functionality of the Mongoose Connection get() method. We are accessing value of userName property that we configured on connection object. First, we are extracting it and storing it in a variable named userName than we are displaying it using console.log().

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('userName', 'gfg')
  
// Fetching property value using get() method
const userName = connectionObject.get('userName');
console.log(userName);


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

node app.js

Output:

gfg

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads