javascript - 更新/删除节点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);
})
}
解决方案
Textarea 字段的 ID 应该是唯一的。
推荐阅读
- google-analytics - Google Analytics 4 事件参数
- python - 熊猫 DataFrame 的 Modin 与线程
- python - Pandas 列表列,为每个列表附加一个新列
- c# - c# RegEx 匹配在哪一行。林克?
- python - 如何让 NaN 在带有 astropy 的水稻压缩 FITS 文件中工作?
- python - Python MySQL 更新查询
- python - 如何在 django 表单中以干净的功能获取请求的用户?
- r - R中二进制运算的非数字参数错误,需要解释
- php - 如何从 docker-compose 设置 prestashop 数据库服务器?
- jmeter - 如何为 JMeter + Tauras 执行禁用 trace.jtl