Basic backend with Node, Express, and MongoDB

delgadociterio
2 min readMar 2, 2021

In my last post, I introduced some of the most common concepts of Node. Now, let’s create something more useful, a local database and API.

The repo is in the following link

https://github.com/delgadociteriowa/node-01-basic-backend

For the database, there are many different options, but for this tutorial, we will be using MongoDB:

Create a new folder ‘api-rest’ (or with another name), and create a now node project with npm init. Once it is created, in order to develop an API in an easy way, we will need a popular framework, Express.

npm install express — save

With express, with just a few lines of code, we can have a server up and running:

Inside the project, index.js:

‘use strict’

const express = require(‘express’);

const app = express();

app.listen(5000, () => {

console.log(‘API Running in localhost 5000’)

})

Console:

node index.js

In order to interact with a database, first, you must start the database system, in this case mongo:

Console:

mongod

Our API will need a library for easily connect to the database system. In order to connect with Mongo, we will need to install mongoose:

npm i -S mongoose

Once mongoose is installed, you will need to connect your API with Mongo. The following code is an example of that:

mongoose.connect(‘mongodb://localhost:27017/shop’, (err, res) => {

if (err) {

return console.log(‘DB connection error: ‘, err)

}

console.log(‘DB Connected’);

app.listen(5000, () => {

console.log(`API Running in localhost ${port}`);

})

})

Before going directly to the CRUD part of our API, first, let’s create a model folder with the Schema of objects we want to store in the database. For this example, the objects are going to be products for a store:

models/product.js

‘use strict’

const mongoose = require(‘mongoose’);

const Schema = mongoose.Schema;

const ProductSchema = Schema({

name: String,

picture: String,

price: { type: Number, default: 0},

category: {

type: String,

enum: [‘computers’, ‘phones’, ‘accesories’]

},

description: String

});

module.exports = mongoose.model(‘Product’, ProductSchema);

Then we import the product Schema in our index.js:

const mongoose = require(‘mongoose’);

const Product = require(‘./models/product’);

So now, we can use it in our get, post, put and delete methods:

app.get(‘/api/product’, (req, res) => {

Product.find({}, (err, products) => {

if (err) return res.status(500).send({ message: `Request error: ${err}`});

if (!products) return res.status(404).send({message: ‘There are no existances’});

res.status(200).send({ products })

})

});

The other methods are in the repository.

And this is basically all you need in order to create a basic RESTful API.

Happy Hacking!

--

--