【发布时间】:2020-07-18 08:46:18
【问题描述】:
我需要有关如何从帖子中删除单个评论的帮助。当我点击删除它返回500 error。这里让我感到困惑的一些事情是,如果我在链接上同时传递帖子和评论 ID,我将如何告诉 Ajax 这个是用于发布的,而这个是用于评论的。
这是我的帖子架构
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
from: {
type: String,
required: true
},
createdAt: {
required: true,
default: Date.now
},
postImage: {
type: String,
require: true
},
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]
})
这是我的 main.js 文件中的 ajax。
/deleting comment with Ajax
$(document).ready(function() {
$('.delete-comment').on('click', function(e) {
const $target = $(e.target);
const id = $target.attr('data-id');
$.ajax({
type: 'DELETE',
url: '/posts/comments/'+id,
success: function(response) {
window.location.href='/posts';
},
error: function(err){
console.log(err);
}
});
});
});
我的路线/cmets
//Delete comment inside a post
router.delete( '/comments/:id', function( req, res ){
const post = Post.findOne({_id: req.params.postId});
const ObjectId = mongoose.Types.ObjectId;
let query = {_id:new ObjectId(req.params.id)}
console.log(query)
post.comments.delete(query, function(err) {
if(err){
console.log(err);
}
res.send('Success');
});
})
我的意见/index.ejs
//Comments and link
<% const counter = post.comments.length >= 2 ? "Comments" : "Comment"; %>
<button class="show-comments"><%= post.comments.length + " " + counter + "" %></button>
<% %>
<div class="postcomments" ><% post.comments.forEach(item => { %>
<ul >
<li><%= item.description %></li>
<a class="delete-comment" href="#" data-id="<%=item._id%>">Delete</a>
</ul>
<% });%>
我的 app.js
//use route from app.js
var commentRouter = require('./routes/comments');
app.use('/posts', commentRouter);
这是我的终端上返回的内容
DELETE /posts/comments/5e8ad7121277855e656b3379 500 5.395 ms - 3698
【问题讨论】:
-
我们如何知道您要删除哪条评论?为此,您需要 postId 和 commentId 吗?您还可以将您的帖子架构添加到问题和示例文档中吗?
标签: node.js ajax express mongoose