Open In App

Mongoose Schema Connection.prototype.id API

Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose Schema API Connection.prototype.id of the Mongoose API is used on the Connection objects. It allows us to check how many connections does connection object poses. It is used to debug the connection object when we have multiple connections pointing to one single connection reference. Let us understand the id property using an example.

Syntax:

connectionObject.id;

Parameters: This property does not accept any parameters.

Return Value: This property returns a number that represents the number of database connection of the particular connection object.

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: 

 

Example 1: In this example, we are illustrating the functionality of id property on the connection object. We have created 3 connections that are pointing to the same variable and at the end with the help of id property, we verify the number of connections pointing to the connectionObject variable.

Filename: app.js

Javascript




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


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

node app.js

Output:

3

Example 2: In this example, we are illustrating the functionality of id property on connection object.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
  
// Set Up the Database connection
const connectionObject = mongoose.createConnection(URI);
  
console.log(connectionObject.id)


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

node app.js

Output:

1

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



Last Updated : 15 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads