In this tutorial, we'll learn how to connect a Node.js application with MongoDB. Node.js is a powerful JavaScript runtime built on Chrome's V8 JavaScript engine and MongoDB is a document-oriented NoSQL database, both are widely used in modern web application development.
You will learn:
Prerequisites:
We will be using mongoose
, a MongoDB object modeling tool designed to work in an asynchronous environment. It provides a straight-forward, schema-based solution to model your application data.
Steps:
Install mongoose: You can install mongoose
by running npm install mongoose
in your terminal.
Import mongoose: In your main server file, import mongoose using const mongoose = require('mongoose');
.
Connect to MongoDB: Use mongoose.connect()
to connect to your MongoDB database.
Example 1: Connecting to MongoDB
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("We're connected!");
});
In this snippet, we first import mongoose and then we connect to MongoDB running on localhost with the database name test
. The mongoose.connect()
function takes two arguments: a connection string and an options object.
The db.on('error')
event will be triggered if there is a connection error. The db.once('open')
event will be triggered once when the connection is open.
In this tutorial, you've learned how to connect Node.js with MongoDB using mongoose
. You've also learned how to handle connection events.
Next Steps:
mongoose
Additional resources:
Exercise 1: Connect to a MongoDB database named 'practice'.
Exercise 2: Handle a connection error by printing a custom error message.
Exercise 3: Print a custom success message once the connection is open.
Solutions:
Solution 1:
mongoose.connect('mongodb://localhost/practice', {useNewUrlParser: true, useUnifiedTopology: true});
Solution 2:
db.on('error', function() {
console.error('There was a connection error!');
});
Solution 3:
db.once('open', function() {
console.log("Successfully connected to the database!");
});
Tips for further practice: