我正在嘗試洗掉對帖子的評論,但找不到該評論。當我在時,console.log(post.comments)它會向我顯示所有評論,但我仍然找不到評論。錯誤是Comment not found我寫的,發現評論仍然存在或不存在。但是評論在那里,我將 id 與它匹配。幫幫我,我是 NodeJs 的新手。幫我解決這個問題
*作為前端,我正在使用 react 和 redux 我認為問題出在后端,我也用郵遞員進行了測驗。無法洗掉郵遞員的評論。
這是評論路線和控制器
router.route('/:id/comment/:comment_id').delete(protect, deleteComment);
export const deleteComment = asyncHandler(async (req, res) => {
const post = await Post.findById(req.params.id);
const comment = post.comments.find(
(comment) => comment._id === req.params.comment_id
);
if (!comment) {
res.status(404);
throw new Error('Comment not found');
}
//Check User
if (comment.user.toString() === req.user._id.toString()) {
post.comments = post.comments.filter(
({ id }) => id !== req.params.comment_id
);
await post.save();
return res.json(post.comments);
} else {
res.status(401);
throw new Error('User not authorized');
}
});
這是后模型
import mongoose from 'mongoose';
const postSchema = mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: [true, 'Please Author is required'],
},
title: {
type: String,
required: true,
},
desc: {
type: String,
required: true,
},
img: {
type: String,
},
isLiked: {
type: Boolean,
default: false,
},
isDisLiked: {
type: Boolean,
default: false,
},
likes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
],
disLikes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
],
comments: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
text: {
type: String,
required: true,
},
name: {
type: String,
},
pic: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
},
],
categories: {
type: Array,
},
},
{
timestamps: { createdAt: 'created_at', updatedAt: 'modified_at' },
}
);
const Post = mongoose.model('Post', postSchema);
export default Post;
uj5u.com熱心網友回復:
當您訪問時,_id您正在訪問ObjectId的實體
您應該嘗試與 進行比較id,即 的字串表示_id
const comment = post.comments.find(
(comment) => comment.id === req.params.comment_id
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370887.html
標籤:javascript 节点.js 反应 MongoDB 猫鼬模式
上一篇:改變徽章的顏色-條件
