javascript - MongoDB:为什么评论(数组)属性上的 Array.find 返回未定义?
问题描述
可能是一个愚蠢的问题,但为什么在这种情况下 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']
很可能是 type ObjectID
,它永远不会等于 a string
。在比较之前显式调用toString()
函数(或使用其他方法转换为 a string
):
comment => comment['id'].toString() === commentId
推荐阅读
- javascript - Formset management_form 刷新后给出错误的 TOTAL_FORMS 值
- python - 合并两个 DataFrame 但更新原始列
- python - 如何重新导入字典对象而不在当前会话中进行修改?
- html - 不使用表单标签时,angularjs如何检测$dirty?
- mapbox - Maxbox GL JS Popup 打开事件未按预期工作
- python-3.x - Python中的大写字母和标点符号
- javascript - 将特定按钮与特定模式链接
- vb.net - 如何让我的系统自动关闭并重新打开?
- php - 如何处理codeigniter中的sub_query?
- javascript - 从 URL 获取令牌