首页 > 解决方案 > 更新/删除节点js中的评论

问题描述

当用户单击编辑评论并提交编辑表单时,我正在尝试更新用户的评论。但是当有来自同一个用户的多个评论时,评论更新请求进来,节点 js 更新该用户的第一个评论。(我的删除评论操作也有同样的问题)。有人可以帮助解决这个问题吗?

这是我的ejs代码

<% article.comments.forEach(comment => { %>
            <div class="my-3">
                <strong><%= comment.author.username %></strong>
                <span class="float-right">
                    <%= comment.created.getHours() %>:<%= comment.created.getMinutes() %>
                    <%= comment.created.getMonth() + 1 %>/<%= comment.created.getDate() %>/<%= comment.created.getYear() + 1900 %>
                </span>
                <p><%= comment.content %></p>
                <% if(user && comment.author.id.equals(user._id)) { %>
                    <a  class="btn btn-sm btn-warning float-left mr-2" 
                        onclick="toggleEditForm(`<%= comment._id %>`)">
                        Edit
                    </a>
                    <form id="delete-form" action="/articles/<%= article._id %>/comments/<%= comment._id %>?_method=DELETE" method="POST">
                        <button class="btn btn-sm btn-danger">Delete</button>
                    </form>
                <% } %>
            </div>
            <div id="<%= comment._id %>" style="display: none;">
                <form action="/articles/<%= article._id %>/comments/<%= comment._id %>?_method=PUT" method="POST">
                    <div class="form-group">
                        <label for="inputContent">Edit comment</label>
                        <textarea class="form-control" name="content" id="inputContent" rows="3" placeholder="Type here"><%= comment.content %></textarea>
                    </div>
                    <input type="submit" class="btn btn-primary" value="Edit Comment">
                </form>
            </div>
        <% }) %>

而我的节点 js 控制器更新评论和删除评论方法

exports.putUpdateComment = (req, res, next) => {
    const content = req.body.content;
    const author = {
        id: req.user._id,
        username: req.user.username
    };
    const newComment = {
        content: content,
        author: author
    };
    Comment.findOneAndUpdate(req.params.commentId, newComment)
        .then(updatedComment => {
            req.flash('success', 'Your comment was updated');
            res.redirect('/articles/' + req.params.id);
        })
        .catch(err => {
            const error = new Error(err);
            error.httpStatusCode = 500;
            return next(error);
        })
};

exports.deleteComment = (req, res, next) => {
    Comment.findOneAndRemove(req.params.commentId)
        .then(() => {
            req.flash('success', 'Comment was deleted');
            res.redirect('/articles/' + req.params.id);
        })
        .catch(err => {
            const error = new Error(err);
            error.httpStatusCode = 500;
            return next(error);
        })
}

标签: javascriptnode.jsexpressejs

解决方案


Textarea 字段的 ID 应该是唯一的。


推荐阅读