MongoDB:为什么对注释(数组)属性的Array.find返回未定义?

时间:2019-10-08 21:47:15

标签: javascript mongodb mongoose

可能是一个愚蠢的问题,但是在这种情况下,为什么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 });
}

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

在下面的片段中工作正常,这些片段是从您的帖子中复制的! 我假设您是pd.DateOffset,而不是df.index - pd.DateOffset(seconds=0.5) print(df) DatetimeIndex(['2018-01-22 21:38:59.500000', '2018-01-22 21:39:00.500000', '2018-01-22 21:39:02.500000', '2018-01-22 21:39:05.500000', '2018-01-22 21:39:06.500000', '2018-01-22 21:39:07.500000', '2018-01-22 21:39:08.500000', '2018-01-22 21:39:09.500000', '2018-01-22 21:39:10.500000', '2018-01-22 21:39:11.500000'], dtype='datetime64[ns]', name=0, freq=None) ?检查拼写错误

posts.comments

答案 2 :(得分:0)

您可以使用:

const result = comments.find(
  ({ id }) => id === commentId,
);
console.log(result)
// should return { id: '5d9b137ff542a30f2c135556', addedBy: '5b8528131719dc141cf95c99' }