如何对子文档执行操作,而不需要在Mongoose中获取父文档

How to perform operation on subdocuments without fetching a parent in Mongoose?

本文关键字:文档 Mongoose 不需要 获取 执行 操作      更新时间:2023-09-26

现在,如果我想删除子文档,我这样做:

Post.findById(post_id).exec(function(err, post) {
  post.comments.remove({'_id': comment_id});
  post.save(function(err) {
    res.end("Hooray!");
  });
});

这似乎对我来说不是最优的,因为每次我删除一个评论,整个帖子将从DB提取,它有很多东西附加到它。那么,有没有可能在不获取父文档的情况下修改子文档呢?

根据文档,如果你想更新文档而不获取它,你必须手动执行更新请求。在我的例子中,它将导致以下代码:

Post.update({'_id': post_id}, {$pull: {'comments': {'_id': comment_id}}}).exec(function(err){
  console.log('Hooray!');
});

这是一个很好的可行的解决方案,但是执行直接请求意味着验证不会像版本控制那样好。