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 });
}
qqilihq
comment => comment['id'] === commentId

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

为什么我的find方法返回未定义?

来自分类Dev

Mongodb find()返回未定义的(node.js)

来自分类Dev

属性返回未定义

来自分类Dev

MongoDB返回未定义

来自分类Dev

为什么innerHTML返回“未定义”?

来自分类Dev

为什么返回未定义状态?

来自分类Dev

为什么函数返回未定义?

来自分类Dev

为什么 .forEach 返回未定义?

来自分类Dev

为什么我使用“ This”参数从Find()获得“未定义”返回值?

来自分类Dev

JavaScript属性返回未定义

来自分类Dev

长度属性返回“未定义”

来自分类Dev

对象属性返回未定义的(nodejs)

来自分类Dev

id属性返回null或未定义

来自分类Dev

jQuery最近属性返回未定义

来自分类Dev

HTMLElement属性返回未定义-角度

来自分类Dev

JavaScript属性返回未定义

来自分类Dev

id属性返回null或未定义

来自分类Dev

jQuery最近属性返回未定义

来自分类Dev

属性返回表中未定义的

来自分类Dev

MongoDB排序返回未定义

来自分类Dev

JSON数组数据返回未定义

来自分类Dev

声明的数组返回未定义

来自分类Dev

比较数组函数返回未定义

来自分类Dev

Javascript数组元素返回未定义

来自分类Dev

访问数组的索引返回未定义

来自分类Dev

JSON数组项返回未定义

来自分类Dev

JSON数组数据返回未定义

来自分类Dev

数组返回“未定义”结果

来自分类Dev

映射数组返回未定义的值