Hey, Express! Meet Mongoose
Tags: javascript, mongoose, beginners, express
Published: 2020-09-21 22:34:14

When I first started learning Express, I was overwhelmed by all the new terms that I had to learn. I found myself having to learn about Node.js and Express, MongoDB and Mongoose, view engines, and middleware functions. Also, I realized that I needed to develop a sense of knowing which dependencies to use best for building my apps.

However, instead of succumbing to “*Oh, my! What I’ve gotten myself into*!” feeling I decided to take a deep breath and try to tackle one thing at a time, and started with Mongoose.

**Hello Mongoose**

I think the simplest definition to Mongoose is, it is a module/library that helps us connect to MongoDB, which is [a NoSQL]( https://www.mongodb.com/nosql-explained) database system, to create and access data using more readable, easy to manage schemas and queries.

Five main steps we take to start working with Mongoose:

1. Define/design your models.
2. Connect to MongoDB.
3. Create Schemas.
4. Make models of these schemas.
5. Use these models to create (or then update or delete) the documents (records) you want to store in the database.

**Step 1: Define your Models**

When we build an app we need to define what kind of models we should have based on the app we are building. Then we need to specify the properties that we need for each of these models.

Here, we will define two models for a tiny, little blog app, **User** and **Post**. 
For **User**, the properties are *username* and *email*. 
For **Post**, the properties are *title*, *content*, *author*, and *created_at*. 

**Step 2: Connect to MongoDB**
I am using [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) for this step. 

- After [signing up](https://account.mongodb.com/account/register), choose Create a Cluster.
![create-Free-Cluster](https://i.ibb.co/8d0m7hj/create-Free-Cluster.jpg) 

- Click the Create Cluster button (the one fixed at the bottom). 

- Wait a few minutes for the cluster to be ready and then click CONNECT.
![connect cluster](https://i.ibb.co/2vBvfjP/cluster0.jpg)

- Click the Allow Access from Anywhere button.
![all access from anywhere](https://i.ibb.co/k5dsJ44/allow-access-from-anywhere.jpg)

- Click the Add IP Address button. 
![app IP address](https://i.ibb.co/CsRvsgz/add-ip-address.jpg)

- Add a username and password to your database and click Create Database User and then the Choose a connection method button at the bottom. We will need the username and password to connect to the database later.

![add a username and password](https://i.ibb.co/zSgT97m/create-user.jpg)
- Click Connect your application 
![Connect your application](https://i.ibb.co/Ntj46tR/connect-your-application.jpg)

- Then Copy and save the link somewhere. 
![copy the database link](https://i.ibb.co/kyVzPqW/copy-link.jpg)

**Note**: Replace `<username>` and `<password>` with your database username and password. And since we did not name the database, replace `<dbname>` with the default name`cluster0`.

```javascript
// here's how my link looks
/*"mongodb+srv://hajarnasr:mydbpassword@cluster0.cszse.mongodb.net/cluster0?retryWrites=true&w=majority" */
```
Now let us write some code.

`cd` to your project, `yarn init` and then `yarn add express mongoose nodemon`.

Create `app.js` at the root of your project.

```javascript
// app.js
const express = require("express");
const mongoose = require('mongoose');

// initiate an express app
const app = express();

// The link to the database. Note that this link should be in a .env file to make it more secure.
const MongoUri = "mongodb+srv://hajarnasr:mydbpassword@cluster0.cszse.mongodb.net/cluster0?retryWrites=true&w=majority";

// connect to the database 
mongoose.connect(MongoUri, { 
                           useNewUrlParser: true,  
                           useUnifiedTopology: true
                        }, 
                        (err)=>{
                            err? 
                              console.log(err)
                            :
                            // let me know when the database is connected
                            console.log("Connected successfully!")
                       });

// add a root route to the app and send "Hello Mongoose"
app.get("/", (req, res)=>{
    res.send("Hello Mongoose")
});

// set up the server
app.listen(3000, ()=> {
    console.log("Server up: http://localhost:3000");   
});
```
In the `cmd` run `nodemon app`.

Now, if you go to [http://localhost:3000/](http://localhost:3000/), you should see "Hello Mongoose" on your screen and "Connected successfully!" in the console.

Our database is now connected, and we are ready to move to the next step. We are ready to create a few Schemas.

**Refrences**
[freeCodeCamp](https://www.freecodecamp.org/learn/apis-and-microservices/mongodb-and-mongoose/)
[the mongoosejs docs](https://mongoosejs.com/docs/guide.html).
[MDN](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose)
[code.tutsplus](https://code.tutsplus.com/articles/an-introduction-to-mongoose-for-mongodb-and-nodejs--cms-29527#:~:text=These%20documents%20are%20saved%20inside,via%20the%20Model's%20schema%20definition.)