node.js博客文章添加评论不起作用



当我向任何博客文章中添加评论时,它不起作用。这是一个普通的node.js MVC控制器,链接到路由:

    commentBlog(req, res) {
      const comment = {
        comment: req.body.comment,
        author: req.params.id
      }
      Comment.create(comment, (error, comment) =>  {
        if (error) {
          console.log(error);
        } else {
          Blog.findById(req.params.id, (error, blog) => {
            blog.comments.push(comment);
            console.log(comment);
            blog.save((error, savedBlog) => {
              if (error) {
                console.log(error);
              } else{
              res.redirect('/blogs/' + blog._id);
            }
        })
         })
        }
      })
      };

(这是模型) ----------------------------- const mongoose = require('mongoose'), 架构= mongoose.schema;

var commentSchema = new Schema({
    author: { type: Schema.Types.ObjectId, ref: 'user' },
    comment: {type: String},
    created: {type: Date, default: Date.now},
    blog: { type: Schema.Types.ObjectId, ref: 'blog' }
});
var Comment = mongoose.model('comment', commentSchema);
module.exports = Comment;

this is the ejs file
---------------------
<body>
 <% if(blog) { %>
<form action="/blogs/<%= blog._id %>/comment" method="POST">
    <textarea name="comment[text]"
        rows="10" cols="50">Write something here
    </textarea>
    <input type="submit" value="Post comment">
    </form>
 <% } %>

**i don't know why it doesn't display when i add like to any post it just 

不工作**

好吧,您没有在ejs文件中显示博客内容。仅渲染表格。您应该渲染博客字段供他们显示。以下是显示博客标题的示例(前提是博客对象中有一个标题字段)。

    <body>
     <% if(blog) { %>
    <h2><%= blog.title %> </h2>
    <form action="/blogs/<%= blog._id %>/comment" method="POST">
        <textarea name="comment[text]"
            rows="10" cols="50">Write something here
        </textarea>
        <input type="submit" value="Post comment">
        </form>
<% } %>

然后,您可以使用上面的示例在博客对象中显示其他字段。

最新更新