无法在Express和Mongoose中更新博客应用程序

时间:2019-02-16 21:52:23

标签: node.js mongodb express mongoose

我正在使用CRUD操作建立一个博客站点。我可以创建,阅读和删除,但是在弄清楚如何更新创建的帖子时遇到了困难。基本上,我可以在其中单击 home.ejs 中单个条目的“编辑”按钮,并进入 edit.ejs 路由,在该路由中输入字段将被填充当前标题和内容。我希望能够编辑内容和标题,然后在 edit.ejs 路由上单击“发布”以更新内容。但是当我这样做时,它给了我一个错误:无法发布/编辑,并且没有任何更新。我要执行的操作是更新单个条目,然后重定向回根路由并反映出编辑内容。在“ app.post(“ / edit /:id”)”路径上,我应该使用“ PUT”请求来更新帖子吗?如果很难遵循,对不起。我不太善于解释事物。我已经为此花了很长时间。任何帮助表示赞赏。

以下是相关代码:

app.js

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const _ = require("lodash");

const aboutContent = "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Non diam phasellus vestibulum lorem sed. Platea dictumst quisque sagittis purus sit. Egestas sed sed risus pretium quam vulputate dignissim suspendisse. Mauris in aliquam sem fringilla. Semper risus in hendrerit gravida rutrum quisque non tellus orci. Amet massa vitae tortor condimentum lacinia quis vel eros. Enim ut tellus elementum sagittis vitae. Mauris ultrices eros in cursus turpis massa tincidunt dui.";
const contactContent = "Scelerisque eleifend donec pretium vulputate sapien. Rhoncus urna neque viverra justo nec ultrices. Arcu dui vivamus arcu felis bibendum. Consectetur adipiscing elit duis tristique. Risus viverra adipiscing at in tellus integer feugiat. Sapien nec sagittis aliquam malesuada bibendum arcu vitae. Consequat interdum varius sit amet mattis. Iaculis nunc sed augue lacus. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. Pulvinar elementum integer enim neque. Ultrices gravida dictum fusce ut placerat orci nulla. Mauris in aliquam sem fringilla ut morbi tincidunt. Tortor posuere ac ut consequat semper viverra nam libero.";

let app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/blogDB", {
  useNewUrlParser: true
});

const postSchema = {
  date: String,
  title: String,
  content: String
}

const Post = mongoose.model("Post", postSchema);

app.get("/", (req, res) => {

  Post.find({}, (err, posts) => {
    res.render("home", {
      posts: posts
    });
  });
});

app.get("/about", (req, res) => {
  res.render("about", {
    aboutContent: aboutContent
  });
});

app.get("/contact", (req, res) => {
  res.render("contact", {
    contactContent: contactContent
  });
});

app.get("/compose", (req, res) => {
  res.render("compose");
});


app.post("/compose", (req, res) => {
  const postTitle = req.body.postTitle;
  const postBody = req.body.postBody;

  let date = new Date();
  let postDate = date.toLocaleString('en-US');

  const post = new Post({
    date: postDate,
    title: postTitle,
    content: postBody
  });

  post.save(err => {
    if (!err) {
      res.redirect("/");
    }
  });
});

app.get("/edit/:id", (req, res) => {
  const requestedId = req.params.id;
  console.log(req.body);
  Post.findOne({
    _id: requestedId
  }, (err, post) => {
    if (!err) {
      res.render("edit", {
        title: post.title,
        content: post.content
      });
    }
  });
});

app.post("/edit/:id", (req, res) => {
  const requestedId = req.params.id;
  console.log(req.body);
  Post.findOne({
    _id: requestedId
  }, (err, post) => {
    if (!err) {
      res.render("edit", {
        title: post.title,
        content: post.content
      });
    }
  });
});



app.get("/posts/:id", (req, res) => {
  const requestedId = req.params.id;

  Post.findOne({
    _id: requestedId
  }, (err, post) => {
    if (!err) {
      res.render("post", {
        title: post.title,
        content: post.content
      });
    }
  });
});

app.post("/delete", (req, res) => {
  const deletePost = req.body.delete;

  Post.findByIdAndDelete(deletePost, (err) => {
    if (!err) {
      res.redirect("/");
    }
  });
});

app.listen(3000, function () {
  console.log("Server started on port 3000");
});

home.ejs

<%- include("partials/header") -%>
<h1>Home</h1>
<a href="/compose" class="post-link"><button type="button" class="new-entry btn btn-dark">New Entry</button></a>

<div class="entries-container">
  <% posts.forEach(post => { %>

  <div class="blog-entry">
    <p class="post-date">Posted on
      <%= post.date %>
    </p>
    <h2>
      <%= post.title %>
    </h2>
    <div class="entry-footer">
      <a href="/posts/<%= post._id %>" class="post-link"><button type="button" class="btn btn-outline-primary">VIEW</button></a>
      <form action="/edit" method="POST">
        <a href="/edit/<%= post._id %>" class="post-link" ><button type="button" name="edit" value="<%= post.title %>" class="btn btn-outline-secondary">EDIT</button></a>
      </form>
      <form action="/delete" method="POST">
        <button type="submit" name="delete" value="<%= post._id %>" class="btn btn-outline-danger">DELETE</button>
      </form>
    </div>
  </div>
  <% }) %>
</div>

<%- include("partials/footer") -%>

edit.ejs

<%- include("partials/header") -%>
<h1>Compose</h1>
<form action="/edit" method="PUT">
  <div class="form-group">
    <label for="postTitle">Title</label>
    <input type="text" name="postTitle" class="form-control" id="postTitle" autocomplete="off" value="<%= title %>">
    <label for="postBody">Post</label>
    <textarea name="postBody" class="form-control" autocomplete="off" rows="8"><%= content %></textarea>
  </div>
  <button type="submit" name="button" class="btn btn-primary">Publish</button>
</form>
<%- include("partials/footer") -%>

post.ejs

<%- include("partials/header") -%>
  <h2 class="post-title"><%= title %></h2>
  <p class="post-content"><%= content %></p>
<%- include("partials/footer") -%>

1 个答案:

答案 0 :(得分:0)

通常,如果要进行更新,则要使用PUT,如果要创建新项,则要使用POST,但是老实说,这些词并不能强制行为,而是要编写的代码会。

在您的代码中,您在/ edit /:id上声明了一个get和post,这不一定是错误的,但是它们都具有相同的代码。

如果我要创建博客文章编辑器,则应按照以下方式定义路线:

GET - /blog-获取所有博客

GET - /blog/:id-获得一个博客

POST - /blog-创建一个新博客

PUT - /blog/:id-更新现有博客

DELETE - /blog/:id-删除现有博客

对于您的表单,您已将操作设置为PUT,但在快速申请中没有声明相应的PUT路线。

在猫鼬中,更新现有项目的最简单方法是使用.findOne(),并在回调函数中根据需要更改对象,然后调用.save()