MongoDB and Express : Your Guide to Mastering Your CRUD
Tags: mongodb, express, node
Published: 2023-06-10 03:01:28

Hello there, If you're looking to connect MongoDB server on Windows to an Express server and perform full CRUD operations, you've come to the right place. Let's embark on this journey together!

_The steps should be the same on other system configurations. More about my port later__

## Step 1: Downloading MongoDB Community Edition

First things first, we need to download MongoDB Community Edition. Head over to the MongoDB download center at:
`https://www.mongodb.com/try/download/community`
Choose the version that suits your operating system and download the installer.
_I will be installing on windows because i enjoy the front end software they provide and its the easiest thing i have found_

## Step 2: Installing MongoDB Community Edition

Once the installer is downloaded, run it and follow the instructions. The default settings should be fine for most users.
Take note of the version you are installing. The current version is 6.0.6 so my server file will be named 6.0
_As mentioned I will be using __MongoDb Compass__ that is included in the installer so make sure to use it for this guide_

## Step 3: Verifying the Installation

After the installation is complete, let's make sure MongoDB is installed correctly.
Open a command prompt and type the following command: `>mongo --version`
This should display the version of MongoDB that you installed.
_if this fails i dont knoe ... ask Chat-GPT_

## Step 4: Changing the Server IP
By default, MongoDB listens for connections from localhost. If you want to change the IP address that MongoDB listens on in order to allow remote access, you'll need to modify the MongoDB configuration file, mongod.cfg.
_I will be connecting from my __wsl 2__ client so I will need to change to my local networks ipv4_

Open the mongod.cfg file in a text editor. This file is typically located in `C:\Program Files\MongoDB\Server\<Your Version>\bin\mongod.cfg` on Windows systems.

Find the network section in the configuration file. It should look something like this:

    # network interfaces
    net:
      port: 27017
      bindIp: 127.0.0.1

The bindIp option specifies the IP addresses that MongoDB listens on. To change this, replace 127.0.0.1 with the IP address that you want MongoDB to listen on. For example, to make MongoDB listen on all IP addresses, you would change this line to bindIp: 0.0.0.0.

## Step 5: Restarting MongoDB
After changing the server IP, you'll need to restart MongoDB for the changes to take effect. You can restart MongoDB by restarting the MongoDB service easily from the command line by running the following command in a command prompt with administrative privileges:

`> net stop MongoDB`
`> net start MongoDB`

### Step 6: Import Data:
Now open up MongoDb Compass and create a new connection to your <bindIp>:<port>
From here we can create a new database, mongodb provides a few options, on my larger databases I prefer to use clustered indexes.Whereas smaller databases (around 300k documents) will usually be fine with the standard type.
Mongodb will store each object as a "document" in your database, so we will use the import button in the collection we created to import either json or csv data. MongoDb will work its magic and within seconds we can have a fully queryable database of hundreds of thousands of objects of various schemas.

## Step 6: Connecting MongoDB to an Express Server

Now that we have MongoDB set up, let's connect it to an Express server on Wsl. We'll use the mongodb package's MongoClient to establish a connection.

1. Install Packages:
    - In your terminal, run the following command to install the required packages:
      `$ npm install express mongodb`

2. Create Server File
    - In your terminal, run the following command to create your server's app.js file:
      `$ touch app.js`
3. Add Boilerplate Code:
 
            const express = require('express'); // Import Express
            const MongoClient = require('mongodb').MongoClient; //Import Mongo
            const app = express(); // Define our server application process
            const port = 3000; // Define our port
            
            const url = "mongodb://localhost:27017/mydb";
            
            MongoClient.connect(url, function(err, db) {
              if (err) throw err;
              console.log("Database created!");
              db.close();
            });
            
            app.listen(port, () => {
              console.log(`Server running at http://localhost:${port}`);
            });

## Step 7: Performing CRUD Operations

Lastly, let's create routes to handle our CRUD (Create, Read, Update, Delete) operations. These routes will direct incoming requests to the appropriate database operations.

    app.get('/users', (req, res) => {
      // Fetch users from the database
      db.collection('users').find({}).toArray((err, result) => {
        if (err) throw err;
        res.send(result);
      });
    });
    
    app.post('/users', (req, res) => {
      // Add a new user to the database
      const newUser = req.body;
      db.collection('users').insertOne(newUser, (err, result) => {
        if (err) throw err;
        res.send(`Successfully added new user: ${newUser.name}`);
      });
    });
    
    app.put('/users/:id', (req, res) => {
      // Update a user in the database
      const userId = req.params.id;
      const updatedUser = req.body;
      db.collection('users').updateOne({_id: userId}, {$set: updatedUser}, (err, result) => {
        if (err) throw err;
        res.send(`Successfully updated user with id: ${userId}`);
      });
    });
    
    app.delete('/users/:id', (req, res) => {
      // Delete a user from the database
      const userId = req.params.id;
      db.collection('users').deleteOne({_id: userId}, (err, result) => {
        if (err) throw err;
        res.send(`Successfully deleted user with id: ${userId}`);
      });
    });
And there you have it! You've successfully set up MongoDB, connected it to an Express server, and performed full CRUD operations. You're now a MongoDB-Express.js maestro! Remember, the key to mastering these technologies is practice and exploration. So, keep experimenting, keep coding, and most importantly, keep having fun with it. Happy coding!