GithubHelp home page GithubHelp logo

express-mongodb's Introduction

REST api with Express and MongoDB

A brief description of quick start rest api with express and MongoDB.

Installation

  1. First create a directory and run npm init to create package.json file.

  2. Now install express and nodemon. nodemon needs to execute and run the server

npm install express nodemon
  1. add following script on package.json to run the server.
"scripts":{
    "start":"nodemon server.js"
}
  1. Create server.js file to the root directory with following code.
const express= require('express')

const app = express()

//Routes
app.get('/',(req,res)=>{
    res.send('Here is a simple api route')
})

app.get('/posts',(req,res)=>{
    res.send('Here is the posts endpoint of the api')
})

//server will start listening to the mentioned port
app.listen(5000)
  1. Run npm instal mongoose to install mongoose for mongodb database connection.
  2. Now use mongoose in server.js to connect the database.
const mongoose= require('mongoose')

//Connect to DB
mongoose.connect('http://localhost:27000/',()=>
    console.log('Connect to db')
)
  1. Now install dotenv package to get out db connection from .env file by this command.
npm install dotenv
  1. Create a .env file and shift the db connection into it and use it into server.js file by writing following code.

.env

DB_CONNECTION=mongodb+srv://username:[email protected]/?retryWrites=true&w=majority

server.js

require('dotenv/config')

//Connect to DB
mongoose.connect(process.env.DB_CONNECTION,()=>
    console.log('Connect to db')
)
  1. We can separate the routes to their own file and import them into server.js file. posts.js
const express= require('express')
const router = express.Router();

// Routes
// reveal on http://localhost:5000/posts
router.get('/',(req,res)=>{
    res.send('Here is the posts route')
})

//  http://localhost:5000/posts/post99
router.get('/post99',(req,res)=>{
    res.send('Here is the posts 99')
})
module.exports=router

server.js

const express= require('express')
const app = express()
const mongoose= require('mongoose')
require('dotenv/config')

//Import Routes
const postsRoute=require('./routes/posts')

//Middleware [mulitple Middleware can be used for different router]
app.use('/posts',postsRoute)

//Routes
app.get('/',(req,res)=>{
    res.send('We are on base directory')
})


//Connect to DB
mongoose.connect(process.env.DB_CONNECTION,()=>
    console.log('Connect to db')
)

//server will start listening to the mentioned port
app.listen(5000)
  1. Now we need a Posts model with mongoose. Create models>Post.js file. In Post.js we'll create Post Schema. Post.js
const mongoose=require('mongoose')

const PostSchema= mongoose.Schema({
    title:{
        type:String,
        required:true
    },
    description:{
        type:String,
        required:true
    },
    date:{
        type:Date,
        default: Date.now
    }

    //also could be written as this wihtout validation
    // title:String,
    // description:String,
    // date:Date
})


module.exports= mongoose.model('Posts',PostSchema)
  1. Install body-parser package to parse the body data into json.
npm install body-parser
  1. Add a post route in routes>posts.js.Then add this bodyParser middleware into server.js file so that we can get POST request's request body in json.

posts.js

const express= require('express')
const router = express.Router();
const Post = require('../models/Post')

//Routes
//reveal on http://localhost:5000/posts

router.get('/',(req,res)=>{
    res.send('Here is the posts route')
})

//  http://localhost:5000/posts/post99
router.get('/post99',(req,res)=>{
    res.send('Here is the posts 99')
})


router.post('/',(req,res)=>{
    const post = new Post({
        title: req.body.title,
        description: req.body.description
    })

    post.save()
        .then(data=>{
            res.json(data)
        })
        .catch(err=>{
            res.json({message:err})
        })
})

module.exports= router

server.js

const express= require('express')
const app = express()
const mongoose= require('mongoose')
const bodyParser=require('body-parser')
require('dotenv/config')

//Import Routes
const postsRoute=require('./routes/posts')


//Middleware
app.use(bodyParser.json()) //everytime we hit any url this bodyparser will run

app.use('/posts',postsRoute)



//Routes
app.get('/',(req,res)=>{
    res.send('Here is a simple api route')
})


//Connect to DB
mongoose.connect(process.env.DB_CONNECTION,()=>
    console.log('Connect to db')
)

//server will start listening to the mentioned port
app.listen(5000)
  1. Now add get, delete, and update method to the posts.js
const express= require('express');
const { restart } = require('nodemon');
const router = express.Router();
const Post = require('../models/Post')

//Routes
//reveal on http://localhost:5000/posts
//Gets back all the post
router.get('/',async (req,res)=>{
    try{
        const posts= await Post.find()
        res.json(posts)
    }
    catch(err){
        res.json({message:err})
    }
})

//  http://localhost:5000/posts/post99
router.get('/post99',(req,res)=>{
    res.send('Here is the posts 99')
})

//SUBMITS A POST
router.post('/',(req,res)=>{
    const post = new Post({
        title: req.body.title,
        description: req.body.description
    })

    post.save()
        .then(data=>{
            res.json(data)
        })
        .catch(err=>{
            res.json({message:err})
        })
})

//GET SPECIFIC POST
router.get('/:postId',async (req,res)=>{
    try{
        // console.log(req.params.postId)
        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)=>{
    try{
        // console.log(req.params.postId)
        const removePost=await Post.remove({_id: req.params.postId})
        res.json(removePost)
    }
    catch(err){
        res.json({message:err})
    }
})

//UPDATE A POST
router.patch('/:postId',async (req,res)=>{
    try{
        // console.log(req.params.postId)
        const updatePost=await Post.updateOne({_id: req.params.postId},{$set:{title:req.body.title}})
        res.json(updatePost)
    }
    catch(err){
        res.json({message:err})
    }
})


module.exports= router
  1. Install cors to enable cross domain fetching for api.
npm install cors

After installing package just add cors middleware in server.js

const cors=require('cors')

app.use(cors())

Acknowledgements

express-mongodb's People

Watchers

Imamul Islam nAyeem avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.