MongoDB
- Install mongoose, a package built on the `mongodb` native driver, to interact with the MongoDB instance and model the data from express/node application.
npm install mongoose
- Install MongoDB
Whether you are a Linux, Windows, or Mac User, the official docs provide a simple procedure to install MongoDB on your local machine.
Click Here for Installation:- Windows | Ubuntu | macOS | Others
After installation, you will be able to use MongoDB in your terminal, also you can install mongo compass a GUI application to interact with the database.
- Integrate with the express application
Explanation:- First of all we will import the mongoose module and then later we call the connect method, it accepts a connection string, and object with some configurations, The “ExpressIntegration” written inside the connection string is the random name of the Database, the rest all stuff comes under syntax. This method provides a promise in return that’s why we are using then and catches block. On the successful connection with the database, it will call the listen to method with the app object to start the express server otherwise simply will execute a console log on failure.
// Filename - app.js
//Importing modules
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = 3000;
//Connection to the mongodb database
mongoose.connect('mongodb://localhost:27017/ExpressIntegration')
.then(()=>{
app.listen(PORT, ()=>{
console.log("Database connection is Ready "
+ "and Server is Listening on Port ", PORT);
})
})
.catch((err)=>{
console.log("A error has been occurred while"
+ " connecting to database.");
})
Output: Start the server with the `node app.js` command and this will be output in the terminal, which means we are successfully able to integrate the MongoDB database.
Access Cloud Service
Go to mongodb.com and register/sign in yourself, and check out the mongodb cloud, after then you’ll see something like this,
Here click on connect, and then it will ask for some configurations like whether you want to use a cloud database for a mongo shell, an application, or Mongo Compass(a GUI). We will choose to connect your application. Later it will ask you about driver and version, choose node.js and the latest version.
And finally, it will provide a string, that will be used to integrate this database into an express server. It also provides a Web User Interface to monitor and configure the database.
Now just simply replace the earlier localhost string with this one. With this all, your cloud database is ready to use.
Database Integration in Express.js
Express is a minimalistic framework that works along with Node.js and provides salient features to run a backend server and much more. As you know the database plays a vital role in a fully working application to persist data. In this article, we are going to discuss how we can integrate a database in a server that is working upon the Express.js framework.