Node.js Mongoose – Connect to MongoDB

To connect to MongoDB from Node.js using Mongoose package, call connect() function, on the variable referencing to mongoose, with MongoDB Database URI passed as argument to the function.

Get reference to Database

To get a reference to the database specified, use connection() function on Mongoose reference, as shown below :

Is connection successful ?

To check if the connection is successful or not, you may use callback functions : on() and once().

Connection is successful.

To simulate ‘Connection not successful’ scenario, lets change the port to some incorrect value.

If the connection is not successful, you may see the following error message displayed on console.

When the connection is made without any errors and is open, callback function provided to db.open(‘open’, callback) is executed.

Conclusion:

In this tutorial – Node.js Mongoose – Connect to MongoDB, we have learnt to connect to MongoDB using Mongoose, get the reference to Database, check if the connection is successful or not.