Skip to content

Instantly share code, notes, and snippets.

@maggocnx
Last active March 4, 2023 11:26
Show Gist options
  • Save maggocnx/6619965 to your computer and use it in GitHub Desktop.
Save maggocnx/6619965 to your computer and use it in GitHub Desktop.
mongoskin rest api
var express = require('express')
, mongoskin = require('mongoskin')
var app = express()
app.use(express.bodyParser())
var db = mongoskin.db('localhost:27017/skintest', {safe:true});
app.param('collectionName', function(req, res, next, collectionName){
req.collection = db.collection(collectionName)
return next()
})
app.get('/', function(req, res) {
res.send('please select a collection, e.g., /collections/messages')
})
app.get('/collections/:collectionName', function(req, res) {
req.collection.find(req.query,{limit:10, sort: [['_id',-1]]}).toArray(function(e, results){
if (e) return next(e)
res.send(results)
})
})
app.post('/collections/:collectionName', function(req, res) {
req.collection.insert(req.body, {}, function(e, results){
if (e) return next(e)
res.send(results)
})
})
app.get('/collections/:collectionName/:id', function(req, res) {
req.collection.findOne({_id: req.collection.id(req.params.id)}, function(e, result){
if (e) return next(e)
res.send(result)
})
})
app.put('/collections/:collectionName/:id', function(req, res) {
req.collection.update({_id: req.collection.id(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.del('/collections/:collectionName/:id', function(req, res) {
req.collection.remove({_id: req.collection.id(req.params.id)}, function(e, result){
if (e) return next(e)
res.send((result===1)?{msg:'success'}:{msg:'error'})
})
})
app.listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment