Using Nodejs with MongoDB
Tags: mongodb, javascript, node, webdev
Published: 2022-04-24 08:14:07

In this tutorial I'll show you how to interact with a MongoDB database from Node.js.


# Using MongoDB and Node.js

MongoDB is one of the most popular databases used along with Node.js.

We’ll be using the official mongodb npm package. If you already have a Node.js project you are working on, install it using

Fist ensure your system has Node.js version 12 or later and a compatible version of npm (Node Package Manager). For more installation proceed to official Node.js website. 

One this done make a new new folder and run the command
```
npm init 
```
to initalize an empty nodejs project. After this will install MongoDB using the below command. 

```
npm install mongodb
```

To starting using MongoDB in your web appliction you need to first connect your application with the MongoDb server that you can use all functionalists of a MongoDB. 


## Connecting to MongoDB
You require the mongodb package and you get the MongoClient object from it. Create a new file server.js to start our Express.js server. Load mongoose and express by adding the following code to server.js.

```
const express = require("express");
const mongoose = require("mongoose");
const Router = require("./routes")

const app = express();

app.use(express.json());
```
Then connect to a local MongoDB instance using the mongoose.connect() function.

server.js
```
mongoose.connect('mongodb://localhost:27017/usersdb',
  {
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true
  }
);
```
To create a connection to MongoDB atlas, we have to create a new MongoDB cluster. 

Visit the MongoDb atlas website and follow the below steps. 
1. Open your Cluster tab in MongoDb Atlas and click `CONNECT`.
2. Select Connect your application and choose Node.js for the driver.
3. Copy the connection string.

With the connection at hand, create the following variables and replace their values using your actual credentials.

server.js

```
const username = "<mongodb username>";
const password = "<password>";
const cluster = "<cluster name>";
const dbname = "myFirstDatabase";

mongoose.connect(
  `mongodb+srv://${username}:${password}@${cluster}.mongodb.net/${dbname}?retryWrites=true&w=majority`, 
  {
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true
  }
);
```
To check that everything is working as expected, add the following code right below mongoose.connect()

server.js

```
// ...
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", function () {
  console.log("Connected successfully");
});
```

Then, set the app to listen to port 3000.

This way we can connect any Nodejs application with MongoDB. It is easy to use with lots of flexibility in hand. 

Now to upload any data to mongoDB we have to create something called schema. Which is a basic layout of how the data will look like. 

## Creating the schema
Now let’s define a collection schema for our application.

Create another file models.js and add the following code.

models.js

```
const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  age: {
    type: Number,
    default: 0,
  },
});

const User = mongoose.model("User", UserSchema);

module.exports = User;
```

We create a schema UserSchema using the mongoose.Schema() method. The schema collects the name and age fields sent from the request.

## POST endpoint to send data to MongoDB

Create a new file routes.js. This file defines the endpoints for our app.

Load express and the schema we created in Step 3 by adding the following code.

routes.js

```
const express = require("express");
const userModel = require("./models");
const app = express();
```
Then create the POST endpoint by adding the following code.

routes.js

```
// ...
app.post("/add_user", async (request, response) => {
    const user = new userModel(request.body);
  
    try {
      await user.save();
      response.send(user);
    } catch (error) {
      response.status(500).send(error);
    }
});
```
We create a route /add_user to add a new user to the database. We parse the content to be saved to the database using the line const user = new userModel(request.body);.

We then use a try/catch block to save the object to the database using the .save() method.

## To find any element using async/await
```
const find = async () => {
  try {
    const item = await collection.findOne({name: 'Togo'})
  } catch(err => {
  console.error(err)
  })
}

find()
```
# Conclusion
We have looked at how to connect a Nodejs application with MongoDB. We have also looked at how to establish MongoDB schemes and POST requests for our collections.