In this post I’m going to show you how easy it is to create a basic API using Node JS and connect it to a MongoDB instance with automated tests (Test).
Tools I plan on using
- NodeJS
- Express
- JEST
- MongoDB
Creating a basic project
$ mkdir todo
$ cd todo
Initialise a new node app
$ npm init
Install express
$ npm install express —-save
Create an empty app
$ touch app.js
Update app.js
const express = require('express');
// Set up the express app
const app = express();
const todos = [
{
id: 1,
title: "lunch",
description: "Go for lunch by 2pm"
}
];
// get all todos
app.get('/api/v1/todos', (req, res) => {
res.status(200).send({
message: 'Hi John, Here are your todos. You better start doing some work! ;)',
todos: todos
})
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`server running on port ${PORT}`)
});
Run the app
$ node app.js
Go to URL: http://localhost:3000/api/v1/todos
Connect to a mongo DB
Open up a new terminal tab
Install mongod
$ brew install mongodb
Run the DB
$ mongod --config /usr/local/etc/mongod.conf
Go back to the other window and install Mongoose
$ npm install mongoose --save
Mongoose is Nodejs package for modeling Mongodb. It helps you handle validation and business logic for mongodb on Nodejs.
Add in mongoose dependancy to app.js
// Import Body parser
const bodyParser = require('body-parser');
// Import Mongoose
const mongoose = require('mongoose');
// Configure bodyparser to handle post requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Connect to Mongoose and set connection variable
mongoose.connect('mongodb://localhost/todos');
const db = mongoose.connection;
Create a GET todo endpoint
Create a controller
In this controller all we want to do is get all ToDo items that exist in the DataBase.
Create a folder called contollers
$ mkdir contollers
Inside of the models
directory create a file called todoController.js
// todoController.js
// Import ToDo model
const ToDo = require('./../model/todoModel');
// View all ToDo items
exports.findAll = (req, res) => {
ToDo.find()
.then(todos => {
res.send(todos);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving products."
});
});
};
Create a model
In here we want to create a model of our ToDos and create a schema for it.
Create a folder called contollers
$ mkdir models
Inside of the models
directory create a file called TodoModel.js
// TodoModel.js
const mongoose = require('mongoose');
// Setup schema
const toDoSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
}
});
module.exports = mongoose.model('todo', toDoSchema);
Update the route
Remove the old get function and replace with this
const todoController = require('./controllers/todoController.js');
app.get('/api/v1/todos', todoController.findAll);
Create a new todo
Inside your controller.js
add in the following
exports.create = (req, res) => {
// Create a Product
const todo = new ToDo({
title: req.body.title,
description: req.body.description,
});
// Save Product in the database
todo.save()
.then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while creating the ToDo item."
});
});
};
Create an endpoint to post data to it.
Inside your app.js
add in the following
// Post a todo item
app.post('/api/v1/todo', todoController.create);
Final files.
todoController.js
// Import contact model
const ToDo = require('./../model/todoModel');
// View all ToDo items
exports.findAll = (req, res) => {
ToDo.find()
.then(todos => {
res.send(todos);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving products."
});
});
};
exports.create = (req, res) => {
// Create a Product
const todo = new ToDo({
title: req.body.title,
description: req.body.description,
});
// Save Product in the database
todo.save()
.then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while creating the ToDo item."
});
});
};
todoModel.js
// TodoModel.js
const mongoose = require('mongoose');
// Setup schema
const toDoSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
}
});
module.exports = mongoose.model('todo', toDoSchema);
POST to the todo
api
{
"title": "lunch",
"description": "Go for lunch by 2pm"
}