Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose

crud-restapis-with-nodejs-express-mongodb-feature-image

In the tutorial, we show how to build CRUD RestAPIs with NodeJS/Express and MongoDB using Mongoose.

Related posts:
NodeJs/Express RestAPIs – POST/GET/PUT/DELETE requests
NodeJs/Express MongoDB One-to-Many related models

Goal

Prerequisites: Create NodeJs/RestAPIs tutorial

-> Project structure:

Objective: design, create models and interact with MongoDB by Mongoose.

-> The tutorial will create a project as below structure:

Mongoose

Mongoose is a MongoDB object modeling tool that provides a schema-based solution to model data. Mongoose is installed in your project (package.json) by commandline:

How to define a Mongoose’s schema for JavaScript object and connect with MongoDB?

Customer Object:

-> Mongoose’s schema, connect & save document to MongoDB:

Practice

Create NodeJs/Express project

Following the guide to create a NodeJS/Express project.

Install Express/Body-parse/Mongoose by commandline:

-> ‘package.json’ :

Mongoose interact with MongoDB
Mongoose Schema

Configure MongoDB’s URL

In the root folder, create a file ‘app/config/mongodb.config.js’ as below content:

Connect to MongoDB

In the ‘server.js’ file , configure mongodb connection:

Full ‘server.js’ file:

Implement CRUD APIs
Routes

In the root folder, create a file ‘app/routes/customer.routes.js’ as below content:

Controllers

In root folder ‘nodejs-restapi’, create a controller folder ‘/app/controllers’. Then create a file ‘/app/controllers/customer.controller.js’ that contains methods for executing above URL requests:

Run & Check results

Run the NodeJs/Express project:

Use Postman to check result ->

– POST a customer:

nodejs-mongodb-create document

nodejs-mongodb-restapi-validation error model

– GET all customers:

nodejs-mongodb-fetch all documents

– GET a customer by id:

nodejs-mongodb-get a document

– PUT a customer:

nodejs-mongodb-put a document

– DELETE a customer:

nodejs-mongodb-restapi-delete a document

nodejs-mongodb-fetch all customers

Sourcecode

NodeJs-RestApi-MongoDB

By grokonez | April 8, 2018.

Last updated on September 28, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*