Skip to content

Instantly share code, notes, and snippets.

@lmas3009
Created January 29, 2021 15:29
Show Gist options
  • Save lmas3009/93e65b1fa8413098c4849713606a0e39 to your computer and use it in GitHub Desktop.
Save lmas3009/93e65b1fa8413098c4849713606a0e39 to your computer and use it in GitHub Desktop.
Rest API using MEN (MongoDB,ExpressJs and NodeJs)
import express from 'express'
import mongoose from "mongoose"
import Cors from 'cors'
import Cars from './Cars'
var app = express()
var port = process.env.PORT || 8080
app.use(express.json())
app.use(Cors())
var Connection_url = 'mongodb+srv://Rest-API_lmas:<password>@cluster0.gklyj.mongodb.net/<dbname>?retryWrites=true&w=majority'
mongoose.connect(Connection_url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
app.get("/", function (req, res){
res.send( "Welcome to Tutorial of REST API using MongoDB, ExpressJS and NodeJS");
})
app.get("/Cars", function (req, res) {
try {
Cars.find((err, data) => {
if (err) {
res.status(500).send(err)
}
else {
res.status(200).send(data)
}
})
} catch (error) {
console.log(error);
}
})
app.post("/Cars_add", function (req, res) {
const dbfeed = req.body
try {
Cars.create(dbfeed, (err, data) => {
if (err) {
res.status(500).send(err)
}
else {
res.status(201).send(data)
}
})
} catch (error) {
console.log(error);
}
})
app.listen(port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment