Javascript MongoDB:为什么Array.find on comments(数组)属性返回未定义?

Javascript MongoDB:为什么Array.find on comments(数组)属性返回未定义?,javascript,mongodb,mongoose,Javascript,Mongodb,Mongoose,可能是一个愚蠢的问题,但在这种情况下,为什么Array.find方法不能按预期工作?我试图查询一个特定的注释,这涉及从数据库中获取具有comments属性的post文档。正是从这个comments数组中,我想提取所说的comment对象。不管出于什么原因,下面的代码都不起作用。为什么? 下面是代码片段 // Post document from which the comments are extracted const post = await Post.findById(postId).po

可能是一个愚蠢的问题,但在这种情况下,为什么Array.find方法不能按预期工作?我试图查询一个特定的注释,这涉及从数据库中获取具有comments属性的post文档。正是从这个comments数组中,我想提取所说的comment对象。不管出于什么原因,下面的代码都不起作用。为什么?

下面是代码片段

// 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 });
}

在下面的代码片段中效果很好,是从你的文章中复制的! 我假设在您的案例中是
posts.comments
,而不是
comments.find
?检查打字错误

const注释=[
{“id”:“5d9b137ff542a30f2c135556”,“添加人”:“5b8528131719dc141cf95c99”},
{“id”:“5d9b0ba2f28afc5c3013d4df”,“addedBy”:“5b8528131719dc141cf95c99”},
{“id”:“5d9b0c26f28afc5c3013d4e0”,“添加人”:“5b8528131719dc141cf95c99”}
];
//例如,如果commentId为“5d9b137ff542a30f2c135556”
//结果注释对象应该是{“id”:“5d9b137ff542a30f2c135556”,“addedBy”:“5b8528131719dc141cf95c99”}
const commentId=“5d9b137ff542a30f2c135556”;
//但是,commentToDelete未定义
const commentToDelete=comments.find(comment=>comment[“id”]==commentId);
console.log(commentToDelete)您可以使用:

const result = comments.find(
  ({ id }) => id === commentId,
);
console.log(result)
// should return { id: '5d9b137ff542a30f2c135556', addedBy: '5b8528131719dc141cf95c99' }
您的
comment
子文档来自MongoDB/Mongoose,因此
comment['id']
可能属于
ObjectID
类型,它永远不等于
字符串。在比较之前,显式调用
toString()
函数(或使用其他方法转换为
字符串
):

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

@DhananjaiPai看到了,复制的代码工作得很好。在发布这个问题之前我也试过了。无论出于何种原因,相应的控制器在我的express应用程序中不起作用。我已经编辑了这个问题以包含完整的代码。是的!我是个白痴。我怎么忘了这个?哦,好吧。谢谢今天也发生在我身上。两次;-)这是mongo查找,而不是javascript查找!?因为javascript中没有ObjectId类型!它是
Array.prototype.find()
,但是
id
ObjectId
类型。
comment => comment['id'].toString() === commentId