尝试建立从mongoDB删除个人资料和用户的途径

时间:2020-09-23 12:34:25

标签: javascript node.js mongodb express

这是我在StackOverflow上的第一篇文章:)。

我已经明确表示要删除该用户及其个人资料:

// @route   DELETE api/profile/
// @desc    Delete user and profile
// @access  Private
router.delete(
  '/',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    Profile.findOneAndDelete({ user: req.user.id })
      .then(() => {
        console.log(req.user.id);
        User.findOne({_id: req.user.id }).then(user=>console.log(user));
        User.findOneAndDelete({ _id: req.user.id });
      })
      .then(() => {
        res.json({ success: true });
      });
  }
);

使用用户的令牌从Postman发出删除请求后,我获得了成功响应,但是当我检查MongoDB时,配置文件消失了,但是用户仍然在那里。

我的第一个菜鸟主意是问题出在护照上,我没有找回正确的身份证件。我错了ofc,配置文件不见了,我添加的2 console.log返回的是正确的用户ID和用户:

5f6a380f874e5c2fe454ac10
{
  _id: 5f6a380f874e5c2fe454ac10,
  name: 'test Testeson',
  email: 'test@test.com',
  password: '$2a$10$uiq7Q080gS/.4xEbF2W/cuXG2MgnacqObKTLezUyuHBI0qnFB1Dca',
  date: 2020-09-22T17:44:47.254Z,
  __v: 0
}

然后我认为这是一个javascript异步问题,我盯着它看了很长时间,但我没有看到这个问题,我什至试图用await async进行重构并将整个回调函数包装在async中包装纸。没必要。

我什至检查了MongoDB用户的权限,但是没关系,当然,配置文件已删除... 猫鼬用户模式是这样的:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = User = mongoose.model('user', UserSchema);

也许这是一个愚蠢的小错误,但是我已经被困了好几个小时了……

任何帮助将不胜感激,

谢谢你,:)

2 个答案:

答案 0 :(得分:1)

尝试将.then()块添加到findOneAndDelete()并查看。

User.findOneAndDelete({ _id: req.user.id }).then();

对于我来说,如果then块不存在,那么操作也不会成功,添加完then块之后,只有这些操作才能成功执行。

答案 1 :(得分:0)

尝试重构您的代码以改为使用异步/等待,并查看其是否有效。您可能不正确地链接了.then()。我写这样的东西:

router.delete(
  '/',
  passport.authenticate('jwt', { session: false }),
  async (req, res) => {
    const { id } = req.user;
    try {
      await Profile.findOneAndDelete({ user: id });
      await User.findOneAndDelete({ _id: id });
      res.json({ message: "Success" });
    } catch(e) {
       res.sendStatus(500)
    }
  }
);

让我知道这是否对您有用。