12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- const mongoose = require("mongoose");
- const express = require("express");
- const Schema = mongoose.Schema;
- const app = express();
- const jsonParser = express.json();
-
- const userScheme = new Schema({name: String, message: String}, {versionKey: false});
- const UserMessage = mongoose.model("UserMessages", userScheme);
-
- app.use(express.static(__dirname + "/public"));
-
- mongoose.connect("mongodb://localhost:27017/messagesDB", { useUnifiedTopology: true, useNewUrlParser: true}, function(err){
- if(err) return console.log(err);
- app.listen(3001, function(){
- console.log("Сервер ожидает подключения...");
- });
- });
-
- app.get("/api/messages", function(req, res){
-
- UserMessage.find({}, function(err, messages){
-
- if(err) return console.log(err);
- res.send(messages)
- });
- });
-
- app.get("/api/messages/:id", function(req, res){
-
- const id = req.params.id;
- UserMessage.findOne({_id: id}, function(err, messages){
-
- if(err) return console.log(err);
- res.send(messages);
- });
- });
-
- app.post("/api/messages", jsonParser, function (req, res) {
-
- if(!req.body) return res.sendStatus(400);
-
- const userName = req.body.name;
- const userMessage = req.body.message;
- const userMessageItem = new UserMessage({ name: userName, message: userMessage});
-
-
- userMessageItem.save(function(err){
- if(err) return console.log(err);
- res.send(userMessageItem);
- });
- });
-
- app.delete("/api/messages/:id", function(req, res){
-
- const id = req.params.id;
- UserMessage.findByIdAndDelete(id, function(err, message){
-
- if(err) return console.log(err);
- res.send(message);
- });
- });
-
- app.put("/api/messages", jsonParser, function(req, res){
-
- if(!req.body) return res.sendStatus(400);
- const id = req.body.id;
- const userName = req.body.name;
- const userMessage = req.body.message;
- const newMessageItem = {message: userMessage, name: userName};
-
- UserMessage.findOneAndUpdate({_id: id}, newMessageItem, {new: true}, function(err, message){
- if(err) return console.log(err);
- res.send(message);
- });
- });
|