-
Notifications
You must be signed in to change notification settings - Fork 90
/
express.js
60 lines (49 loc) · 1.73 KB
/
express.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
var express = require('express'),
mongoskin = require('mongoskin'),
bodyParser = require('body-parser')
logger = require('morgan')
var app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(logger('dev'))
var db = mongoskin.db('mongodb://@localhost:27017/test', {safe:true})
app.param('collectionName', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
app.get('/', function(req, res, next) {
res.send('please select a collection, e.g., /collections/messages')
})
app.get('/collections/:collectionName', function(req, res, next) {
req.collection.find({} ,{limit: 10, sort: {'_id': -1}}).toArray(function(e, results){
if (e) return next(e)
res.send(results)
})
})
app.post('/collections/:collectionName', function(req, res, next) {
req.collection.insert(req.body, {}, function(e, results){
if (e) return next(e)
res.send(results)
})
})
app.get('/collections/:collectionName/:id', function(req, res, next) {
req.collection.findById(req.params.id, function(e, result){
if (e) return next(e)
res.send(result)
})
})
app.put('/collections/:collectionName/:id', function(req, res, next) {
req.collection.updateById(req.params.id, {$set: req.body}, {safe: true, multi: false}, function(e, result){
if (e) return next(e)
res.send((result === 1) ? {msg:'success'} : {msg: 'error'})
})
})
app.delete('/collections/:collectionName/:id', function(req, res, next) {
req.collection.removeById(req.params.id, function(e, result){
if (e) return next(e)
res.send((result === 1)?{msg: 'success'} : {msg: 'error'})
})
})
app.listen(3000, function(){
console.log('Express server listening on port 3000')
})