CRUD application with Express, Mongodb, and Mongoose

·

8 min read

In the article I'm going to over how to build a simple CRUD application with the Framework express, the database is Mongodb then a library called Mongoose to connect Express and Mongodb.

CRUD:

  • Create
  • Read
  • Update
  • Delete

In order to run Express please make Nodejs is install.

Let's begin with making a directory and installing our dependencies. Open your terminal and choose a directory to save this project. Then type this on your terminal.

mkdir crudExpress && cd crudExpress && touch index.js

On the same directory initialize the project:

npm init -y

NPM is package library for Node.js for information about npm packages npmjs.com

Now we can begin by installing our dependencies which are:

npm install express mongoose

There are two files and have been added to your folder which are package.json and package-lock.json. Under the package.json file it should have the dependencies loaded.

Capture.PNG

Open your favorite code editor. VS code you can download it and install it. Visual studio code also has plugins that are useful.

Open Vs code and install a plugin called REST client. Rest client will be used the reach our endpoints.

Let's started writing code. In index.js file going to open our server and have access to the routes. Express allow us to create application express module like so.

const express = require('express');
const app = express();

The variable app will allow us create object with different methods for more information refer to expressjs.com. The first method we going learn about is the listen method.

app.listen([port[, host[, backlog]]][, callback])

The method above basically bind the port and host.

const express = require('express');
const app = express();

app.listen(3000, ()=>{
    console.log("Server connected")
});

All together we should starts the server. On your terminal you should see "Server connected". Now I want to start a database by going to [MongoDB]mongodb.com. Open an account then click on Projects then click on New Project. Choose the free option.

Mongodb.PNG

Scroll to the bottom and name your Cluster as you wish. Then click on create cluster. Create a username and password to authenticate your connection. Then click on Create User.

Connect your id address by clicking on "Add My Current IP Address". Then click on Finish and Create.

After database finishes deployment click on connect.

connect.PNG

Then you want choose "Connect your application". Copy your string connection (Mongo URI) then create a file on Vs code call db.js and paste. Now on our Vs code let's create file a name db.js, in here lets connect the database we created to our project. We going to establish a connection with the mongoose.connect() method for more information on mongoose method please go to mongoose documentation.

mongoose.connect('mongodb://localhost:27017/test').
  catch(error => handleError(error));

// Or:
try {
  await mongoose.connect('mongodb://localhost:27017/test');
} catch (error) {
  handleError(error);
}

One important note whenever connecting to a server if the connections fails you want to emit this error. For more information resource error handling Within the mongoose.connect() we are going to put it async await function. In the db.js file add this code to connect to the database.

const mongoose = require('mongoose');

const connectDB = async () => {
    try {
       await mongoose.connect('Mongon URI');
       console.log('Monogodb connected')
    } catch (error) {
        console.log(error)
        process.exit(1);
    }
}

module.exports = connectDB;

In the index.js we are going to require db.js and call it.

...
const connectDB = require('./db');
connectDB();
...

In the terminal on the same directory we are going to execute our code. Type 'node index.js' on the terminal. The terminal should read 'Server connected' 'Mongodb connect'. We are making sure our connections is connected and no errors. Then press 'control c' to disconnect.

This is the best time to create our endpoints. Lets create a folder called 'routes'. In the folder create file name 'user.route.js'. Before writing in our user.route.js lets use the 'express.Router' class which create a middleware and a routing system in our index.js. Add this code in index.js file.

..
app.use('/', require('./routes/user.route') )
...

In the code we are setting the route the path '/', and the callback function which is located in our 'routes/user.route' folder. For more information about middleware please refer to the middleware path.

Lets jump into our user.route.js file and we are going to called the express Router and send HTTP method. We are using the Router class to create an object with new router object. The Router has the same properties as app.use() method. For more information Router

const express = require('express')

const router = express.Router();


router.get('/', (req, res) => {
        res.send({message: 'successful'})
 })

Now its time to test our endpoint. Create a file named 'api.http'. In the file type in:

GET http://localhost:3000

Here is a screenshot:

apihttp.PNG

Our router it is working properly, lets more endpoints to our 'user.route.js' file. We want to send information to the server which is called a POST HTTP method.

...
router.post('/', (req, res) => {
    res.send({message: 'post successful'})
})
...

Lets add two other HTTP method PUT and DELETE. The PUT method lets us get the information we need and update its value. The PUT and DELETE method takes a param which identify our id.

router.put('/:id', (req, res) => {
    res.send({message: `Update id number ${id}`})
})
router.delete('/:id', (req, res) => {
    res.send({message: `Delete this id number ${id}`})
})

crud.PNG

All of our endpoints work properly now lets create a database schema. A schema is a architecture of our database.(Schema). Press control c to disconnect server and mongo.

In order to form a Schema, first require mongoose library then deconstruct Schema class. Lets define how our schema should like. For our example we are going to create simple name and email. Lastly create a model name the collection and name of the schema. The name of the collection it is what are going to call in our route 'user.route.js' file.

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

const userSchema = new Schema(
    {
        name: {
            type: String,
        }, `
        email: {
            type: String,
        }
    }, {
        timestamp: true
    });

    module.exports = mongoose.model('User', userSchema);

On top of the 'user.route.js' file call the User model. Lets remodel post route, for our callback function we are set it to an asynchronous await function. Inside the function lets create a new instance of User model and supply with HTTP request. In the req submitted in the database contains the information sent. For more information about req.body. After parsing the data in json format then save it to the database.

When we request or response with body we need to parse the data. Express has a method that populate the request object. For more information express.json(). Lets head index.js file and invoke express.json(). We are going use 'app.use()' and for every HTTP method we are going to parse it json format with 'express.json()'.

app.use(express.json());

Now we are ready to populate our database. All of our route is going to change into asynchronous await function. Usually async are wrap inside with try and catch method that catches any error that occurs between sending or receiving. For more information async.

router.post('/', async (req, res) => {
   const user = new User(req.body);
   try {
    await user.save();
    res.send(user);
   } catch (error) {
    console.log(error)
   }
})

Start the server and mongo by typing 'node index.js' in the terminal then head over to 'api.http'. Lets create a post request.

POST http://localhost:3000
content-type: application/json

{
    "name": " Jose",
    "email": "jose@mailer.com"
}

Press 'send request' and it should like this.

post.PNG

Our database should verify our data. On the main dashboard click on Browse Collection then see all our collections.

data.PNG

Lets verify one more time with by using our get method. Rearrange the into async function then lets use Model.find() to get all the data that belongs to the collection User. Then response with the data. Model.find() takes in four parameters and returns a query. For information about Model.find().

router.get('/', async (req, res) => {
    const getUser = await User.find();
    res.send(getUser)
})

get.PNG

Next lets try update our data. First we need to fetch the data we are updating and we are going to mongoose Model.findByIdAndUpate(). The parameters are the id, update object, options, and callback. For more information Model.findByIdAndUpate(). The id of a user its generate by Monogdb and we use that update a user.

router.put('/:id', async (req, res) => {
    const updateUser = await User.findByIdAndUpdate(req.params.id, req.body, {new:true});
    res.status(200).json(updateUser)

})

put.PNG

Lastly lets rearrange our delete method. We are going to do the same and fetch the data and delete from our database. Mongoose has Model.findByIdAndRemove() that deletes the user from collections. For more information about Model.findByIdAndRemove().

router.delete('/:id', async (req, res) => {
    const deleteUser = await User.findByIdAndRemove(req.params.id);
    res.status(200).json(deleteUser);
})

delete.PNG

user.route.js file code

const express = require('express')

const router = express.Router();

const User = require('../model/user.model')

router.get('/', async (req, res) => {
    const getUser = await User.find();
    res.send(getUser)
})

router.post('/', async (req, res) => {
   const user = new User(req.body);
   try {
    await user.save();
    res.send(user);
   } catch (error) {
    console.log(error)
   }
})

router.put('/:id', async (req, res) => {
    const updateUser = await User.findByIdAndUpdate(req.params.id, req.body, {new:true});
    res.status(200).json(updateUser)

})

router.delete('/:id', async (req, res) => {
    const deleteUser = await User.findByIdAndRemove(req.params.id);
    res.status(200).json(deleteUser);
})



module.exports = router;

Finally a simple CRUD application that demonstrate a typical application needs interact with the database. The key take away from this application first creating a server. After the server is open it is available to received and send data. Another is sending HTTP methods that specified what type data but what to do with that data. The second part of this application is to connect with Mongodb database. Then developing a schema and add a collection to the database. Lastly working with REST client api platform.