Skip to content

Instantly share code, notes, and snippets.

@azat-co azat-co/rest-crud.js
Created Jul 28, 2017

Embed
What would you like to do?
const express = require('express')
const logger = require('morgan')
let app = express()
const mongodb= require('mongodb')
const url = 'mongodb://localhost:27017/mean'
const bodyParser = require('body-parser')
app.use(bodyParser.json())
mongodb.MongoClient.connect(url, (error, db)=>{
if (error) return process.exit(1)
app.get('/accounts', (req, res)=>{
console.log(db)
db.collection('accounts')
.find({}, {sort: {_id: -1}})
.toArray((error, accounts)=>{
if (error) return next(error)
res.send(accounts)
})
})
app.post('/accounts', (req, res)=>{
let newAccount = req.body
db.collection('accounts').insert(newAccount, (error, results)=>{
if (error) return next(error)
res.send(results)
})
})
app.put('/accounts/:id', (req, res)=>{
db.collection('accounts')
.update({_id: mongodb.ObjectID( req.params.id)}, {$set: req.body}, (error, results)=>{
if (error) return next(error)
res.send(results)
})
})
app.delete('/accounts/:id', (req, res)=>{
db.collection('accounts').remove({_id:mongodb.ObjectID( req.params.id)}, (error, results)=>{
if (error) return next(error)
res.send(results)
})
})
app.listen(3000)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.