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 60 61 62 63 64 65 66 67
| var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var json = require('json');
//connect to the mongo
var db = require('mongoskin').db("mongodb://localhost/TEST", { w: 0});
db.bind('crds');
//create the app instance
var app = express();
//serve static files
app.use(express.static(path.join(__dirname, 'public')));
//parse POST data
app.use(express.json());
app.use(express.urlencoded());
//response for saving operations
function after_update(err, res, crds){
if (err){
res.status(500);
res.send({ error:err.toString() });
} else {
res.send(record || {});
}
}
//data loading
app.get('/data', function(req, res){
db.crds.find().toArray(function(err, data){
for (var i = 0; i < data.length; i++){
//map _id to id
data[i].id = data[i]._id;
delete data[i]._id;
}
res.send(data);
});
});
//adding
app.post('/data', function(req, res){
db.crds.insert(req.body, function(err, crds){
if (err) {
console.log(err);
return res.send({ status:"error" });
}
res.send({ newid:req.body._id });
});
});
//updating
app.put('/data/:id', function(req, res){
db.crds.updateById(req.param("id"), req.body, function(err){
if (err) return res.send({ status:"error" });
res.send({});
});
});
//deleting
app.delete('/data/:id', function(req, res){
db.crds.removeById(req.param("id"), req.body, function(err){
if (err) return res.send({ status:"error" });
res.send({});
});
});
app.listen(3000); |
Partager