Sitemap

Intro To Mongo with Express JS

8 min readSep 15, 2021

Notes guide :

=> : when we have a code.
== explanation code == : when we explain the code.
[[ additional info ]]: when we have an extra code or extra important information.
{{ external_res }} : when we have external links (videos/tutorials) that support the topic.
<<!!>>: the error with the solution.

What we are going to do is :

  • Install & run Express js
  • Install some dependencies
  • Connect to mongo
  • Do crud operations
  • Test them via postman

To install & run Express js =>

1st : npx express-generator
2nd : npm install
3rd : DEBUG=your app name:* npm start

{{external_res}} :

Let’s install some dependencies :

1st: mongoose

To install mongoose =>

npm install mongoose

{{external_res}} :

2nd: nodemon [locally]=>

npm install --save-dev nodemon

[[ additional info ]]:

nodemon is used to automatically restart node applications when file changes in the directory are detected.

{{external_res}} :

To apply nodemon write inside the script in package.json file=>

“start”: “DEBUG=mongodb-session:* nodemon node ./bin/www”

3rd: body-parser =>

npm install body-parser

[[additional info]] :

body-parser is used to send the request via body instead of the URL.

{{external_res}} :

4th: dotenv =>

npm install dotenv

[[ additional info ]] :

dotenv is used to access the env file from the app.js file

{{external_res}}:

Inside the app.js file, mongoose,body-parser, and dotenv are required in the following way =>

require('dotenv').config()
var mongoose = require('mongoose');
var bodyParser = require('body-parser');

then use body-parser to be able to deal with the body when we have a request=>

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

and create the env file

env file

Then let’s go to mongo atlas and sign in, or sign up if you don’t have an account.

Go to develop and deploy, then create a new project and call it whatever you want, then build a new database.

creating a new database inside mongo

Choose the free choice, then give a name for your cluster and click on ‘create cluster‘.

Once clicked, it should take from 1 to 3 min and your cluster creation will be complete.

To get the connection string that you will put inside the env file to connect mongo to Express, click on the connect button.

Choose Your IP address, then create a username and password to access your database, then click on ‘choose a connection method’.

Now choose ‘connect your application’, then copy the connection string. Don’t forget that you should replace the word ‘password’ with the database password and ‘myfirstdatabase’ with your database name.

Finally, click on close.

Let’s put our connection string and database name inside the env file in the following way :

env file with the connection string

Now, you can create a mongoose connection inside app.js=>

mongoose.connect(process.env.CONNECTION_STRING,{dbName: process.env.dbnam,useNewUrlParser:true,useUnifiedTopology:true,useCreateIndex:true,});

Before we continue I would like to note that we will link the Express project to React as frontend, so we don’t need the files inside the views folder anymore. Make sure to delete anything related to views inside app.js, www file, the index file inside routes, and any other files related to views.

<<!!>> :

If you faced any errors related to mongoose, try changing to mongoose version 5.13.7

{{external_res}} :

User Model :

Let’s create a new folder with the name ‘models’. Inside it, create a file called ‘User.js’

[[ additional info ]]:

  • Every file inside models will represent a table inside your database
  • Inside each model, Schema will represent your table structure and columns[username(string,maxLength,trim),password(string,minLength,trim)…]

Inside User, we will import Schema and model from mongoose as the following =>

const {model, Schema} = require('mongoose');

After that, we will create an instance from Schema as the following =>

const UserSchema=new Schema({})

After that, we will fill this Schema by our structure columns of this table like the following=>

const {model,Schema} = require('mongoose');const UserSchema=new Schema({username:{type: String,unique:true,trim:true,maxLength:100,required:true,},mail:{type:String,unique:true,trim:true,maxLength:100,required:true,lowercase:true,},password:{type:String,trim:true,required:true,minLength:8,},isSuperadmin:{type:Boolean,default:false,},isadmin:{type:Boolean,default:false,},phoneNumber:String,},{
collection:'users'
});

== explanation code == :

  • collection:’users’, means that we are giving a specific name to our table inside the database because sometimes mongo adds ‘s’ to any table name which causes a problem. In my case, I need it to be ‘users’.

Now to benefit from this schema we should put it inside a model and export it as the following =>

let UserModel= model('User',UserSchema);
module.exports=UserModel;

== explanation code == :

  • let UserModel = model(‘User’,UserSchema);
    A user here is representing the name of the model that I will use in my code, not the database table name.

User Controller :

Let’s create a controller folder and inside it, we will put the usersController file

UsersController

Inside it let’s put our functions to get and send data

Functions of UsersController

Now, let’s build the code of our add function and export the file =>

addusers(req, res, next) {
let body=req.body;
let user = new User(body);
user.save((err, res) => {
if (err) return next(err);
res.status(200).send(res);
})
}

In the addusers function, we are sending the data that we will get via body request. That’s why we start with a variable called ‘body’, which will include the body request data. After that we create a new user depending on this data so we write [let user = new User(body);] Finally, to finish and save the creation with handling error possibilities, we write:

[user.save((err, res) => {
if (err) return next(err);
res.status(200).send(res);
})]

Let’s build our get function =>

// read all usersgetAllusers(req, res, next) {User.find({}, (err, response) => {if (err) return next(err);res.status(200).send(response);});}

== explanation code == :

In our getAllusers, the new thing is the find function which, if it comes with void curly brackets, will get all data

Let’s build our update function =>

// update userupdateuser(req, res, next) {let { id } = req.params;let body = req.body;User.updateOne({ _id: id }, {$set: body}, (err, response) => {if (err) return next(err);res.status(200).send(response);});}

== explanation code == :

In our updateuser, the new thing is the updateOne function which will update the database when the id we got from URL params is equal to the user id inside the database

Let’s create the deleteuser function=>

// delete userdeleteuser(req, res, next) {
let { id } = req.params;
User.deleteOne({ _id: id }, (err, response) => {
if (err) return next(err);
res.status(200).send(response);
})
}

== explanation code == :

In our deleteuser, the new thing is the deleteOne function which will delete the user from the database when the id we got from URL params is equal to the user id inside the database.

Finally, we shouldn’t forget to export =>

const User = require('../models/User')class UsersController {// read all users
getAllusers(req, res, next) {
User.find({}, (err, response) => {
if (err) return next(err);
res.status(200).send(response);
});
}
// add a useraddusers(req, res, next) {
let body = req.body;
let user = new User(body);
user.save((err, response) => {
if (err) return next(err);
res.status(200).send(response);
});
}// update user
updateuser(req, res, next) {
let { id } = req.params;
let body = req.body;
User.updateOne({ _id: id }, {
$set: body
}, (err, response) => {
if (err) return next(err);
res.status(200).send(response);
});
}
// delete user
deleteuser(req, res, next) {
let { id } = req.params;
User.deleteOne({ _id: id }, (err, response) => {
if (err) return next(err);
res.status(200).send(response);
})
}
}const usercontroller = new UsersController();
module.exports = usercontroller;

User routes :

To access these methods on our site we should specify a URL that calls them and this will be done inside the routes folder.

So inside routes, in the user file, we will specify the URL to each method that we have in UsersController =>

1st

Let’s require express, UsersController file and call router from the express =>

var express = require('express');
var router = express.Router();
var usersController = require('../Controller/usersController');

2nd

we should call this file inside app.js =>

var usersRouter = require('./routes/users');
app.use('/users', usersRouter);

== explanation code == :

  • first, we are calling the [users] file from routes.
  • second, we are saying that once we have this URL: ’/users’ go and look to ‘users’ file for specific URLs

3rd

Let’s call our functions from UsersController =>

// get users listing.
router.get('/', usersController.getAllusers);
// add user
router.post('/', usersController.addusers);
// update user
router.put('/:id', usersController.updateuser);
// delete user
router.delete('/:id', usersController.deleteuser);

4th

Let’s export =>

module.exports = router;

Postman :

we are almost done, we just need to test our work via postman :

1- add method :

add

2- get method :

get

3- put method(edit) :

put

4- delete method :

delete

Finished!

--

--

No responses yet