ExpressJS deleteroute不更新用户数据



我有一个express控制器来删除正在从页面中删除帖子的用户帖子,而不是从user.posts数据中删除帖子。

function deleteRoute(req, res) {
  Post
    .findById(req.params.id)
    .exec()
    .then((post) => {
      if(!post) return res.status(404).send('Not found');
      return post.remove()
      .then((thisUser)=>{
        if (!Array.isArray(thisUser.posts)) {
          thisUser.posts = [];
        }
        thisUser.posts.slice(post.id);
        thisUser.save();
        res.redirect(`/users/${req.user.id}`);
      });
    })
    .catch((err) => {
      res.status(500).end(err);
    });
}

当我创建帖子时,帖子计数用户的增量计数,但删除时不会减少。我认为这可能是我试图切成帖子的地方正在发生。ID,但我不确定如何修复它。感谢您的任何帮助!

用以下内容修复:

function deleteRoute(req, res, next) {
  Post
    .findById(req.params.id)
    .then((post) => {
      if(!post) return res.notFound();
      return post.remove();
    })
    .then((post) => {
      console.log(post);
      User
      .findById(req.user.id)
      .then((thisUser)=>{
        const index = thisUser.posts[thisUser.posts.length-1];
        console.log('post deleted:' + index);
        if (index === thisUser.posts[thisUser.posts.length-1]) {
          thisUser.posts.splice(index, 1);
          return thisUser.save();
        }
      });
    })
    .then(() => {
      res.redirect(`/users/${req.user.id}`);
    })
    .then(() => res.status(204).end())
    .catch(next);
}

最新更新