You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Mongoose中findOneAndUpdate的FailedToParse错误?

问题分析与解决方案

错误根源

你遇到的FailedToParse(错误码9)问题,核心原因是字段类型不匹配:
你的tokenExp字段在Schema里定义的是数字类型,但你在更新时给它赋值了空字符串"",MongoDB无法将字符串解析为数字,因此更新操作直接失败。

修复步骤

  1. 修正更新值的类型:
    针对tokenExp字段,要使用符合数字类型的有效值。如果你的Schema允许null,可以将其设为null;如果不允许null,可以设为0(表示无效的过期时间),具体取决于你的业务逻辑。

  2. 可选:优化查询配置
    你已经设置了useFindAndModify: false(这是Mongoose 6+的推荐配置),可以在findOneAndUpdate中添加{ new: true }选项,让方法返回更新后的文档(方便后续验证更新结果)。

修正后的代码

router.get("/logout", auth, (req, res) => {
  console.log(req.user.email);
  User.findOneAndUpdate(
    { email: req.user.email },
    { token: "", tokenExp: null }, // 这里将tokenExp改为null(或0,根据Schema调整)
    { new: true }, // 可选,返回更新后的文档
    (err, doc) => {
      if (err) return res.json({ success: false, err });
      return res.status(200).send({ success: true });
    }
  );
});

额外注意事项

  • 检查你的User Schema定义:如果tokenExp设置了required: true,那么不能将其设为null,需要改为0或其他合法数字;如果允许空值,确保Schema中tokenExp的定义包含default: null或nullable: true(取决于Mongoose版本)。
  • useFindAndModify: false不是导致本次错误的原因,这个配置是为了让Mongoose使用MongoDB原生的findOneAndUpdate方法,而非过时的findAndModify,是正确的配置。

内容的提问来源于stack exchange,提问作者Jonathan G.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:58:26