Build a REST API using MongoDB, Express.js and Node.js

  • In package.json file under scripts add the code:
"start": "nodemon server.js"
npm i express
npm i nodemon
npm i cors
npm i mongoose
  • After login top right side you will see a dropdown, click on it and create a new project by clicking on New Project.
  • Now we need to create a cluster by clicking on build a cluster.
  • Now click on connect button in the sandbox and you will see three options to select, select connect your application. By default it will show node.js driver and version of that.
var Connection_url = 'mongodb+srv://Rest-API_lmas:<password>@cluster0.gklyj.mongodb.net/<dbname>?retryWrites=true&w=majority'
  • Now lets connect Connection_url with mongoose and also import the mongoose and cors package.
import mongoose from "mongoose"
mongoose.connect(Connection_url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
  • Now lets create schema for your project.
  • Schema:
    A “Schema” for a database can be compared with the “Class” in object-oriented programming. Just like a class that provides a blueprint for creating objects in a program, a schema provides a blueprint for creating objects (called documents in MongoDB) in a database.
  • Everything in Mongoose starts with defining a schema. It maps directly to a MongoDB collection and defines the structure of the document within that collection.
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array
  • Decimal128
  • Map
  • For Get request:
  • For Post request:
  • Now lets combine all the code:
nodemon server.js
  • Now on top left click on New button you will see two options 1. Create new app, 2. Create new pipeline. Click on Create New app, it will ask you to enter the app-name with there conditions and click Create-app button.
  • Initializing the empty git using git init and follow the steps from heroku website. Create a .gitignore file add this:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store