可能是一个愚蠢的问题,但是在这种情况下,为什么Array.find方法无法按预期工作?我正在尝试查询特定的注释,这涉及从数据库中获取具有注释属性的帖子文档。我要从此注释数组中提取所述注释对象。无论出于何种原因,下面的代码都不起作用。为什么?
以下是代码片段
// Post document from which the comments are extracted
const post = await Post.findById(postId).populate({
path: "comments",
select: "addedBy id"
});
// Resulting post.comments array
[
{ "id": "5d9b137ff542a30f2c135556", "addedBy": "5b8528131719dc141cf95c99" },
{ "id": "5d9b0ba2f28afc5c3013d4df", "addedBy": "5b8528131719dc141cf95c99" },
{ "id": "5d9b0c26f28afc5c3013d4e0", "addedBy": "5b8528131719dc141cf95c99" }
];
// For instance if commentId is '5d9b137ff542a30f2c135556'
// the resulting comment object should be {"id":"5d9b137ff542a30f2c135556","addedBy":"5b8528131719dc141cf95c99"}
// However, commentToDelete is undefined
const commentId = "5d9b137ff542a30f2c135556";
const commentToDelete = comments.find(comment => comment["id"] === commentId);
编辑:这是完整的deleteComment控制器代码
async function deleteComment(req, res, userId, postId, commentId) {
const post = await Post.findById(postId).populate({
path: 'comments',
select: 'addedBy id',
});
const commentToDelete = post.comments.find(
comment => comment['id'] === commentId
);
if (commentToDelete.addedBy !== userId) {
return res
.status(403)
.json({ message: 'You are not allowed to delete this comment' });
}
await Comment.findByIdAndDelete(commentId);
const updatedPost = await Post.findByIdAndUpdate(
post.id,
{ $pull: { comments: { id: commentId } } },
{ new: true, safe: true, upsert: true }
).populate(populateFields);
return res.status(200).json({ updatedPost });
}
comment => comment['id'] === commentId
您的comment
子文档来自MongoDB / Mongoose,因此comment['id']
可能是类型ObjectID
,永远不会等于string
。在比较之前,明确调用toString()
函数(或使用其他方法转换为string
):
comment => comment['id'].toString() === commentId
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句