app.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const mongoose = require("mongoose");
  2. const express = require("express");
  3. const Schema = mongoose.Schema;
  4. const app = express();
  5. const jsonParser = express.json();
  6. const userScheme = new Schema({name: String, message: String}, {versionKey: false});
  7. const UserMessage = mongoose.model("UserMessages", userScheme);
  8. app.use(express.static(__dirname + "/public"));
  9. mongoose.connect("mongodb://localhost:27017/messagesDB", { useUnifiedTopology: true, useNewUrlParser: true}, function(err){
  10. if(err) return console.log(err);
  11. app.listen(3001, function(){
  12. console.log("Сервер ожидает подключения...");
  13. });
  14. });
  15. app.get("/api/messages", function(req, res){
  16. UserMessage.find({}, function(err, messages){
  17. if(err) return console.log(err);
  18. res.send(messages)
  19. });
  20. });
  21. app.get("/api/messages/:id", function(req, res){
  22. const id = req.params.id;
  23. UserMessage.findOne({_id: id}, function(err, messages){
  24. if(err) return console.log(err);
  25. res.send(messages);
  26. });
  27. });
  28. app.post("/api/messages", jsonParser, function (req, res) {
  29. if(!req.body) return res.sendStatus(400);
  30. const userName = req.body.name;
  31. const userMessage = req.body.message;
  32. const userMessageItem = new UserMessage({ name: userName, message: userMessage});
  33. userMessageItem.save(function(err){
  34. if(err) return console.log(err);
  35. res.send(userMessageItem);
  36. });
  37. });
  38. app.delete("/api/messages/:id", function(req, res){
  39. const id = req.params.id;
  40. UserMessage.findByIdAndDelete(id, function(err, message){
  41. if(err) return console.log(err);
  42. res.send(message);
  43. });
  44. });
  45. app.put("/api/messages", jsonParser, function(req, res){
  46. if(!req.body) return res.sendStatus(400);
  47. const id = req.body.id;
  48. const userName = req.body.name;
  49. const userMessage = req.body.message;
  50. const newMessageItem = {message: userMessage, name: userName};
  51. UserMessage.findOneAndUpdate({_id: id}, newMessageItem, {new: true}, function(err, message){
  52. if(err) return console.log(err);
  53. res.send(message);
  54. });
  55. });