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.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name');
Get reference to Database
To get a reference to the database specified, use connection() function on Mongoose reference, as shown below :
var db = mongoose.connection;
Is connection successful ?
To check if the connection is successful or not, you may use callback functions : on() and once().
node-js-mongodb-connection.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/tutorialkart');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connection Successful!");
});
Output
$ node node-js-mongodb-connection.js
Connection Successful!
Connection is successful.
To simulate ‘Connection not successful’ scenario, lets change the port to some incorrect value.
node-js-mongodb-connection.js
var mongoose = require('mongoose');
# incorrect port number
mongoose.connect('mongodb://localhost:ab017/tutorialkart');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connection Successful!");
});
If the connection is not successful, you may see the following error message displayed on console.
Output
$ node node-js-mongodb-connection.js
(node:8986) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Slash in host identifier
(node:8986) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
When the connection is made without any errors and is open, callback function provided to db.open(‘open’, callback) is executed.
Conclusion
In this Node.js 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.