Mongoose Schema API Connection.prototype.readyState
Last Updated :
21 Dec, 2022
The Connection.prototype.readyState property of the Mongoose API is used on the Connection object. It allows us to determine the state of the connection object. Using this method we can identify in which of the following state disconnected, connecting, connected, and disconnecting connection object is currently present. Let us understand readyState property using an example.
The following list represent different connection ready states:
- 0: disconnected
- 1: connecting
- 2: connected
- 3: disconnecting
Syntax:
connection.readyState;
Parameters: This is a property and does not accepts any parameter.
Return Value: This method returns numeric number based on event name which represents the current state of the connection object.
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 readyState property. We are able to track connection object current state using this property.
Filename: app.js
Javascript
const mongoose = require( "mongoose" );
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true ,
useUnifiedTopology: true ,
});
connectionObject.on( 'connected' , () => {
console.log( 'Connected' , connectionObject.readyState);
});
|
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
Connected 1
Example 2: The below example illustrates the basic functionality of the Mongoose Connection readyState property. We are able to track connection object current state using this property. At the end, we are calling close() method in connected event in order to close the connection, and we can see connection object in disconnecting and disconnected state.
Filename: app.js
Javascript
const mongoose = require( "mongoose" );
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true ,
useUnifiedTopology: true ,
});
connectionObject.on( 'connected' , () => {
console.log( 'Connected' , connectionObject.readyState);
connectionObject.close()
});
connectionObject.on( 'disconnecting' , () => {
console.log( 'Disconnecting ' , connectionObject.readyState);
});
connectionObject.on( 'disconnected' , () => {
console.log( 'Disconnected ' , connectionObject.readyState);
});
|
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
Connected 1
Disconnecting 3
Disconnected 0
Reference: https://mongoosejs.com/docs/api/connection.html#connection_Connection-readyState
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...