Browse Source

HW_mongo done

OLGASTUPNIK 3 years ago
commit
eeff3a0dd1
3 changed files with 1812 additions and 0 deletions
  1. 1757 0
      package-lock.json
  2. 8 0
      package.json
  3. 47 0
      server.js

File diff suppressed because it is too large
+ 1757 - 0
package-lock.json


+ 8 - 0
package.json

@@ -0,0 +1,8 @@
+{
+  "dependencies": {
+    "body-parser": "^1.19.0",
+    "express": "^4.17.1",
+    "express-handlebars": "^5.2.1",
+    "mongoose": "^5.11.15"
+  }
+}

+ 47 - 0
server.js

@@ -0,0 +1,47 @@
+const mongoose = require('mongoose')
+const express = require('express')
+const app = express()
+const port = 3000
+const bodyParser = require('body-parser')
+
+mongoose.connect('mongodb://localhost/chat', {useNewUrlParser: true});
+
+let db = mongoose.connection;
+
+let messageSchema = new mongoose.Schema({
+    nick: String,
+    message: String
+});
+
+let Message = mongoose.model('Message', messageSchema);
+
+db.on('error', console.error.bind(console, 'connection error:'));
+
+app.use(bodyParser.json())
+
+app.get('/message', async (req, res) => res.send(await Message.find()))
+app.get('/message/:id', async (req, res) =>
+    res.send(
+        await Message.findOne({_id: mongoose.Types.ObjectId(req.params.id)})
+    )
+)
+
+app.post('/message', async (req, res) => {
+    let newMessage = new Message(req.body)
+    await newMessage.save()
+    res.status(201).send(newMessage)
+})
+
+
+app.patch('/message/:id', async (req, res) => {
+    let msg = await Message.findOne({_id: mongoose.Types.ObjectId(req.params.id)})
+    let patch = req.body
+    Object.assign(msg, patch) // копирует и прото
+    await msg.save()
+    res.status(200).send(msg)
+
+})
+
+
+app.listen(port, () => console.log(`Example app listening on port ${port}!`))
+