RESTful API using NodeJS and MongoDB

Objective
Create a RESTful API using NodeJS and MongoDB. Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser.
Getting started
Prerequisites:
Library |
---|
NodeJS |
MongoDB |
First, check out the environment setup to ensure everything works perfectly. Run npm -v and mongo --version to check the libraries are installed in your machine.
Description
This application implements CRUD (create-read-update-delete) operation by HTTP methods (GET, POST, PUT, DELETE). The CRUD operation performs on three schemas (Professor, ResearchGroup and Student). Moreover, the professors can be searched by designation and research group name. Similarly, the students can be searched by research group name. To check out the schemas and the path definitions, please click the links.
File structure
nodejsREST
|- server.js
|__api
|__controllers
|- professorController.js
|- researchGroupController.js
|- studentController.js
|__models
|- professor.js
|- researchGroup.js
|- student.js
|__routes
|- professorRoutes.js
|- researchGroupRoutes.js
|- studentRoutes.js
Step by step procedure
- Create a folder (e.g., nodejsREST)
- Create package.json
- Run npm init
Package.json is a file that gives the necessary information to npm which allows it to identify the project as well as handle the project's dependencies. Fill out some information regarding the application. - Create a server (e.g., server.js)
- Run npm install express --save to create the node server.
- Run npm install -save-dev nodemon to track the changes and run the server automatically. - Change starting point to nodemon server.js.
- Setting up the schema
- Run npm install mongoose --save to interact with a MongoDB (Database) instance. - Write down the definition
- Definition of database model, route and controller. - Setting up server
- The server is based on express, a minimalistic web framework for nodejs.
- The database connection URL ends with the name of the database (e.g., db).
To start and run the without reloading
Check the mongo daemon is running background. To start the daemon, run mongod. To interact with the mongo shell, run mongo shell. Start the server running npm start. Make sure that, the script has start: server.js in the package.json file.
npm start
Terminal output:
[nodemon] 2.0.4
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting node server.js
MongoDB connection with retry
APP started... on port: 3000
The server is running on http://localhost:3000. Download (postman) OR use command line tool (curl) to execute the operations. The following link has the instructions to execute CRUD in both postman and curl.
Download code: Github