Hello everyone,

Today i am going to show you how to create an api with database access. we use no-sql db, “mongodb” in order to fulfill our requirement. First of all i hope you guys now do have a better understanding about how to create an api with expressJS. If not so please follow my previous blog posts for more details (API Using ExpressJS (GET/POST) , API Using ExpressJS (PUT/DELETE) ).

Since we are using mongodb, we need to configure mongodb first. I Suggest you to follow this amazing tutorial on “How to setup mongodb”. Since i have already installed mongodb in my workspace i am going to start my work.

First open command prompt in your workspace and install dependencies. I hope you can remember how we installed expressJS , body-parser and all earlier day.  In addition to that i am going to install mongoose as my dependency in order to get this job done. Type npm install –save mongoose on you cmd and hit enter. Then package.json will be get updated with new dependency. Now lets create a model to our database.

'use strict';

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
 firstName: String,
 lastName: String,
 birthday: Date
 });

const User = mongoose.model('User', UserSchema);

module.exports = User;

 

 

Now lets create our server.js and put this code in it.

 

'use strict';
 
const bodyParser = require('body-parser'),
 express = require('express'),
 mongoose = require('mongoose');

mongoose.Promise = global.Promise;


const app = express();

app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/expressjsSample', err {
 if (err) {
 console.log(err);
 process.exit(1);
 }
});

const UserModel = require('./user.model');

app.use(express.static(__dirname));

app.get('/', (req, res, next) => {
 res.sendFile('index.html');
});

app.get('/users', (req, res) => {
 UserModel.find().exec().then(users => {
 res.json(users);
 }).catch(err => {
 console.error(err);
 res.sendStatus(500);
 });
});

app.get('/users/:id', (req, res) => {
 UserModel.findById(req.params.id).exec().then(user => {
 res.json(user || {});
 }).catch(err => {
 console.error(err);
 res.sendStatus(500);
 });
});

app.post('/users', (req, res) => {
 const user = new UserModel(req.body);
 user.save().then(user => {
 res.json(user);
 }).catch(err => {
 console.error(err);
 res.sendStatus(500);
 });
});

app.put('/users/:id', (req, res) => {


 const user = new UserModel(req.body);
 user.update().then(() => {
 res.sendStatus(200);
 }).catch(err => {
 console.error(err);
 res.sendStatus(500);
 });
});

app.delete('/users/:id', (req, res) => {
 UserModel.remove(req.params.id).then(() => {
 res.sendStatus(200);
 }).catch(err => {
 console.error(err);
 res.sendStatus(500);
 });
});

app.listen(3000, err => {
 if (err) {
 console.error(err);
 return;
 }
 console.log('app listening on port 3000');
});

Now lets run our program and see the output. Same as before open cmd from you project location and type node server.js and check whether there is a console log saying “app listening on port 3000” or not. If not double check the code you wrote with mine.

If there a message saying server is up then open postman and check our newly created method. In my previous blog post i have mentioned how to call an api from postman so refer it and validate our outputs.

And that is how you connect mongoose with your api. In my next blog post i will share how to call these api from angular services. Till then good bye 🙂

 

Brought to you by Yinza’s Class Room

 

Advertisements