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

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

Troubleshooting the FailedToParse Error in Your Mongoose Logout Endpoint

Hey there, let's break down why your logout route is throwing that FailedToParse error (code 9) and fix it up.

The Root Cause

The error message tells us MongoDB can't parse the update values you're sending. Looking at your code, the issue is with the tokenExp field: you're trying to set it to an empty string (""), but your schema defines tokenExp as a number type. MongoDB rejects this because it can't convert a string to a number automatically for this operation.

Your useFindAndModify: false configuration isn't the problem here—that setting just tells Mongoose to use MongoDB's native findOneAndUpdate instead of the older findAndModify method, which is totally fine.

The Fix

You need to update tokenExp with a value that matches its number type. Here are two common options depending on your schema:

  1. Use null (if your schema allows null values for tokenExp):
    Modify your update object to set tokenExp to null instead of an empty string:

    router.get("/logout", auth, (req, res) => { 
      console.log(req.user.email) 
      User.findOneAndUpdate(
        { email: req.user.email }, 
        { token: "", tokenExp: null },
        { new: true, useFindAndModify: false }, // Explicitly set the option for clarity
        (err, doc) => { 
          if (err) return res.json({ success: false, err }); 
          return res.status(200).send({ success: true }); 
        }
      ); 
    });
    
  2. Use an invalid numeric value (like 0, if null isn't allowed):
    If your schema doesn't permit null for tokenExp, set it to a number that clearly indicates the token is expired (like 0):

    { token: "", tokenExp: 0 }
    

Double-Check Your Schema

Make sure your User schema aligns with the value you choose. For example, if you want to use null, your schema should allow it:

const userSchema = new mongoose.Schema({
  // ... other fields
  token: String,
  tokenExp: {
    type: Number,
    allowNull: true, // Add this if you want to use null
    default: 0 // Optional default value
  }
});

That should resolve the FailedToParse error and let your logout endpoint correctly clear the token fields.

内容的提问来源于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:53:03