MongoDB Connection

Mongoose is used for MongoDB connection, which is an elegant Node.js object data modeling (ODM) library for MongoDB.

We assume you already have installed MongoDB locally & its service is running. Now you need to connect to MongoDB so you need to install “mongoose” at the server side of Node.js application.

cd /mern-alfa/server/
npm install mongoose

Create a directory under the server directory named config and inside it, a file named db.js. In db.js we can add the following code to connect to our database:

import { connect } from "mongoose";

const connectDB = async () => {

try {

     await connect("mongodb://localhost:27017/AlfaDb");

     console.log("MongoDB Connected");

} catch (err) {

     console.error(err.message);

     process.exit(1);

}

};

export default connectDB;

Then import the Mongodb connection to your /mern-alfa/server/server.js file

import connectDB from "./config/db.js";

Also call the connectDB() function as follow

// Connect to MongoDB

connectDB();

Now stop your express server and start again, its will show “MongoDB Connected”

 npm start

> server@1.0.0 start

> node server.js

Server running on port 5000

MongoDB Connected

For details please review code as follow

https://github.com/KoolMonk/mern-alfa/blob/master/server/config/db.js