多个集合修改

Multiple collection modifications

我正在构建一个端点,它将 POSTS 集合中 post 上的 "deleted" 属性 更改为 true(工作正常),然后还可以找到所有评论响应 post 的 COMMENTS 集合(我在不同的路线上做的)并将它们的所有 parentDeleted 属性也更改为 true(这是我遇到麻烦的地方)。

删除post的路径如下:

router.delete('/:id', (req, res) => {
  Post.findById(req.params.id).then(post => {
  post.deleted = true

  post.save().then(post => res.json(post))
  })  
  .catch(err => res.status(404).json({ categories: 'No post found'}))
})

这是查找所有评论以响应 post 的途径:

router.get('/:id/comments', (req, res) => {
  Comment.find({ parentId: req.params.id})
    .then(posts => res.json(posts))
    .catch(err => res.status(404).json({ categories: 'No post found'}))
})

我尝试将评论逻辑添加到 post 逻辑并通过评论进行映射:

router.delete('/:id', (req, res) => {
  Post.findById(req.params.id).then(post => {
    post.deleted = true

    post.save()
  }).then(post => {
    Comment.find({ parentId: req.params.id})
      .then(comments => {
        comments.map((comment) => {
          return comment.parentDeleted = true
       })
    })
  })
  .then(post => res.json(post))   
  .catch(err => res.status(404).json({ categories: 'No post found'}))
})

post的删除状态变为true,但是评论的parentDeleted状态仍然是false。有什么建议么?这是我的第一个问题 posted,所以任何关于礼仪的反馈也将不胜感激。

欢迎,@dcortes!

从您发布的代码看来,您在将评论的 parentDeleted 值更改为 true 后并未保存评论。

因此,对于代码的相关部分,类似于此的内容可能会更好:

Comment.find({ parentId: req.params.id})
  .then(comments => {
    comments.map((comment) => {

      // Set the appropriate value.
      comment.parentDeleted = true;

      // Then save it. 
      // You can modify what is returned, if needed. 
      return comment.save();
   })
})

我不确定保存评论后您想对评论做什么,所以我刚刚返回了 comment.save() 的结果。

请注意,如果您的问题更广泛,"Is it possible to modify multiple collections using one endpoint?"答案肯定是肯定的。