Skip to content

Instantly share code, notes, and snippets.

@azat-co
Created July 28, 2017 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azat-co/b667494bea696c235b8f7a4c780d46c2 to your computer and use it in GitHub Desktop.
Save azat-co/b667494bea696c235b8f7a4c780d46c2 to your computer and use it in GitHub Desktop.
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