Created
July 28, 2017 22:11
-
-
Save azat-co/b667494bea696c235b8f7a4c780d46c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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