How to connect MongoDB with Node.js

How to connect MongoDB with Node.js

Installing Express and Mongoose-

  1. Install the required libraries by running the command:
npm i express
npm i mongoose

Connecting to a Database:

  1. Install nodemon by the following command and answer some basic questions:

     npm i -D nodemon
    
  2. Make two files index.js and db.js

  3. Inside db.js , Connect to MongoDB using mongoose.connect method. This method takes a connection string as the first parameter and options as the second parameter. Here's an example of connecting to MongoDB:

    
     const connectToMongo = () => {
         const mongoose = require("mongoose");
         const Url = 'mongodb://localhost:27017';
         mongoose.connect(Url, {
                 useNewUrlParser: true
             })
             .then(() => {
                 console.log("connected to database mongodb");
             })
             .catch((err) => {
                 console.log("Error", err);
             });
     };
    
    1. Don't forget to export this function ,then In your index.js file add the following command:
  1.  module.exports = connectToMongo;
    
     //index.js
     const connectToMongo = require('./db');
     connectToMongo();
    

    That's it you are successfully connected to MongoDB.

    Setup Express Server:

    Here are the basic steps to set up an Express server:

    1. Install Express by running the command npm install express in your project directory.

    2. Create a new file in your project directory called index.js

    3. Import the Express library at the top of your index.js file using the following code:

       const express = require('express');
      
    4. Create a new instance of the Express application by calling the express() method :

       const app = express();
      
    5. Define a route by calling one of the HTTP methods (e.g. app.get(), app.post(), app.put(), etc.) on your app object. Here's an example of defining a route for the root path of your application:

       app.get('/', (req, res) => {
         res.send('Hello, World!');
       });
      
    6. Start the server by calling the listen() method on your index object. This method takes a port number and an optional callback function as parameters. Here's an example of starting the server on port 3000:

       const port = 3000;
      
       app.listen(port, () => {
         console.log(`Server started on port ${port}`);
       });
      
    7. Run your server by executing the node index.js command in your terminal.

That's it! You now have a basic Express server set up that will respond with "Hello, World!" when you navigate to the root path of your application in a web browser or make a GET request to the root path using a tool like Postman, cURL or thunderclient. You can add additional routes, middleware, and functionality to your server as needed to build out your application.