Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. var express = require('express');
  2. var path = require('path');
  3. var bodyParser = require('body-parser');
  4.  
  5. //connect to the mongo
  6. var db = require('mongoskin').db("mongodb://localhost:27017/test", { w: 0});
  7. db.bind('sites');
  8.  
  9. //create the app instance
  10. var app = express();
  11. //serve static files
  12. app.use(express.static(path.join(__dirname, 'public')));
  13. //parse POST data
  14. app.use(bodyParser.urlencoded({ extended: false }));
  15. // // parse application/json
  16. app.use(bodyParser.json());
  17.  
  18. function after_update(err, res, record){
  19. if (err){
  20. res.status(500);
  21. res.send({ error:err.toString() });
  22. } else {
  23. res.send(record || {});
  24. }
  25. }
  26.  
  27. //data loading
  28. app.get('/data', function(req, res){
  29. db.record.find().toArray(function(err, data){
  30. for (var i = 0; i < data.length; i++){
  31. data[i].id = data[i]._id;
  32. delete data[i]._id;
  33. }
  34.  
  35. res.send(data);
  36. });
  37. });
  38.  
  39. app.post('/data', function(req, res){
  40. db.record.insert(req.body, function(err, record){
  41. if (err) return res.send({ status:"error" });
  42. res.send({ newid:req.body._id });
  43. });
  44. });
  45. app.put('/data/:id', function(req, res){
  46. db.record.updateById(req.param("id"), req.body, function(err){
  47. if (err) return res.send({ status:"error" });
  48. res.send({});
  49. });
  50. });
  51. app.delete('/data/:id', function(req, res){
  52. db.record.removeById(req.param("id"), req.body, function(err){
  53. if (err) return res.send({ status:"error" });
  54. res.send({});
  55. });
  56. });
  57.  
  58. app.listen(3000);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement