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

时间:2017-09-08 14:21:24

标签: node.js model-view-controller controllers

当我向任何博客帖子添加评论时,它不起作用。这是一个正常的Node.js MVC控制器,它链接到route:

    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'),           Schema = 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 

不起作用**

1 个答案:

答案 0 :(得分:0)

好吧,您没有在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>
<% } %>

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