首页 > 解决方案 > 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 });
}

标签: javascriptmongodbmongoose

解决方案


comment => comment['id'] === commentId

您的comment子文档来自 MongoDB/Mongoose,因此comment['id']很可能是 type ObjectID,它永远不会等于 a string。在比较之前显式调用toString()函数(或使用其他方法转换为 a string):

comment => comment['id'].toString() === commentId

推荐阅读