MongoDB问题与从findByID返回的保存值

我在更新密码的功能上遇到问题。我想拥有一个可以更新记录的用户数据的功能。

export const updateMe = async (req,res,next) => {
  if (!req) {
    res.status(400).end()
  }

  try {
    const updatedDoc = await User.findById(req.user._id,function(err,doc) {
      if (err) return next(err)

      doc.password = req.body.password

      doc.save()
    })
      .lean()
      .exec()

    res.status(200).json({ data: updatedDoc })
  } catch (e) {
    console.log(e)
    res.status(400).end()
  }
}

我写了中间件,它将在保存密码之前对密码进行哈希处理。

userSchema.pre('save',function(next) {
  if (!this.isModified('password')) {
    return next()
  }

  bcrypt.hash(this.password,8,(err,hash) => {
    if (err) {
      return next(err)
    }

    this.password = hash
    next()
  })
})

我不知道为什么总是出现错误消息“ doc.save()不是功能”

wensu521 回答:MongoDB问题与从findByID返回的保存值

您正在混合promise和await代码,而且doc.save()返回promise,因此您需要等待它。

(我假设您已经在中间件中设置了req.user._id,并且它不为null。)

因此,如果使用异步/等待,则您的方法必须是这样的:

export const updateMe = async (req,res,next) => {
  if (!req.body.password) {
    return res.status(400).send("Password is required");
  }

  try {
    let updatedDoc = await User.findById(req.user._id);

    updatedDoc.password = req.body.password;

    updatedDoc = await updatedDoc.save();

    res.status(200).json({ data: updatedDoc });
  } catch (e) {
    console.log(e);
    res.status(400);
  }
};
本文链接:https://www.f2er.com/3157832.html

大家都在问