DEV Community

Cover image for How to Create a RESTful API in Node.js using Express, MongoDB
Muhammad Idrees
Muhammad Idrees

Posted on

How to Create a RESTful API in Node.js using Express, MongoDB

A brief guide to creating a RESTful API in Node.js using Express, MongoDB

Step 1: Basic Setup

  • Create a Folder name posts
  • open in vscode or sublime text
  • open (terminal/command prompt) then install the (dependencies/packages)
  • npm init -y
  • npm install express nodemon mongoose dotenv body-parser cors
  • open package.json add this script below in code
"scripts": {
    "start": "nodemon app.js"
  }
Enter fullscreen mode Exit fullscreen mode

Step 2: Setup MongoDB

DB_CONNECTION = mongodb+srv://admin:<password>@cluster0.yarox.mongodb.net/<dbname>?retryWrites=true&w=majority
Enter fullscreen mode Exit fullscreen mode

Step 3: Create Schema

  • Create models folder and create posts.js files
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema({
    title:{
        type: String,
        require:true,
        unique: true 
      },
    description:{
        type: String,
        require:true
      },
    date:{
        type: Date,
        default:Date.now
      }
})

module.exports = mongoose.model('Posts',PostSchema);
Enter fullscreen mode Exit fullscreen mode
  • create User.js inside a models folder
const mongoose = require("mongoose");
let userSchema = new mongoose.Schema({
    name:{
        type: String,
        required:true,
        min:6,
        max:255,
      },
      email:{
          type:String,
          required:true,
          unique: true,
          max:255,
          min:6
      },
      password:{
          type:String,
          required:true,
          max:1024,
          min:6
      },
      date:{
        type: Date,
        default:Date.now
      }

})

module.exports = mongoose.model('users',userSchema);
Enter fullscreen mode Exit fullscreen mode

Step 4: Create Routes

  • create routes folder and create posts.js files
const router = express.Router();
const Post = require('../models/Post')

// get back all the posts
router.get("/",async (req,res)=>{
    try{
const posts = await Post.find();
res.json(posts);
    }catch(err){
res.json({message:err});
    }
})

// submits a post
router.post("/",async (req,res)=>{
    // console.log(req.body)
    const post = new Post({
        title:req.body.title,
        description:req.body.description,
    });
    try{
    const savedPost = await post.save();
    res.json(savedPost);
} catch(err){
    res.json({message:err});
}

})


// specfic Post
router.get('/:postId',async (req,res)=>{
     console.log(req.params.postId)
    try{
        const post = await Post.findById(req.params.postId);
        res.json(post);
    } catch(err){
    res.json({message:err});
}
})


//  Delete Post
router.delete("/:postId",async(req,res)=>{
    console.log(req.params.postId)
    try{
     const removedPost = await Post.remove({_id:req.params.postId});
     res.json(removedPost);
    }catch(err){
        res.json({message:err});
    }
})

//  update a post
router.patch('/:postId',async (req,res)=>{
    try{
    const updatedPost = await Post.updateOne(
        {_id:req.params.postId},
        {$set:{title:req.body.title}}
        );
        res.json(updatedPost);
    }catch(err){
        res.json({message:err});
    }
})

module.exports = router;
Enter fullscreen mode Exit fullscreen mode
  • create auth.js inside a routes folder
const router = require("express").Router();
const User = require('../models/User')

router.post('/register', async (req,res)=>{
    // res.send("register")
    const user = new User({
        name:req.body.name,
        email:req.body.email,
        password:req.body.password
    });
    try{
        const savedUser = await user.save();
        res.status(201).send(savedUser); 
    }catch(err){
        res.status(400).send(err); 
    }
})

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

Step 5: server run

  • create an app.js file in your project folder
const express = require('express');
const app = express();
const PORT = 3000;
const mongoose = require("mongoose")
require('dotenv/config')

// middlewares Routes
const authRoutes = require("./routes/auth")
const postsRoutes = require("./routes/posts")
app.use('/api/user',authRoutes);
app.use('/api/posts',postsRoutes);

// ROUTES
app.get('/',(req,res)=>{
res.send("We are on Home")
})


// connect to DB
mongoose
  .connect(
    process.env.DB_CONNECTION,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex:true
    }
  ).then(() => console.warn("db Connection"));

// db connection end

// listen
app.listen(PORT, () =>
  console.log(`server address: https://localhost:${PORT}`)
);
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
bias profile image
Tobias Nickel

well done