Estoy tratando de eliminar un comentario en una publicación, pero no puedo encontrar el comentario. Cuando estoy en console.log(post.comments) me muestra todos los comentarios pero aún así, no puedo encontrar el comentario. El error fue Comment not found que escribí para encontrar que el comentario todavía está allí o no. Pero el comentario estaba allí, comparé la identificación con él. Ayúdame, soy nuevo en NodeJs. ayúdame a arreglar esto
*Como frontend estoy usando react y redux creo que el problema está en el backend, también lo he probado con el cartero. No se puede eliminar el comentario del cartero.
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;Cuando accede al _id , está accediendo a la instancia del ObjectId
Debe intentar comparar con el id , que es una representación de cadena del _id
const comment = post.comments.find( (comment) => comment.id === req.params.comment_id );