While building an app with ExpressJS that uses MongoDB as the database, you might not have access to the database shell to run your commands. We will use drivers or npm libraries like Mongoose to connect the ExpressJS application with the MongoDB database. This article will understand the syntax and steps involved in connecting ExpressJS to MongoDB with Mongoose.
Installing Mongoose
- To use Mongoose on your Node application you need to first install it in your node_modules folder with npm i mongoose
- It can then be used in the project with const mongoose = require(“mongoose”);
- To connect to a database use:
mongoose.connect(URI, { useNewUrlParser: true, useUnifiedTopology: true, });
- The URI is the Uniform Resource Identifier that helps locate and connect to the database. An example of a URI is mongodb://localhost:27017/dbName where the port number is 27017 (default port number for MongoDB) and dbName is the name of the database.
- mongoose.connect() is promise based so we can run a try-catch block to make sure that the connection is established and catch errors if there are any.
const mongoose = require("mongoose"); mongoose .connect("mongodb://localhost:27017/movieApp", { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => { console.log("Connected to MongoDB:movieApp"); }) .catch((err) => { console.log("Error in connecting to MongoDB"); console.log(err); });
In this post, we have only looked at connecting MongoDB to with an ExpressJS application using Mongoose. To learn about performing CRUD operations on MongoDB from an ExpressJS application, check out this post.