如何修复Mongoose中findOneAndUpdate的FailedToParse错误?
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:
Use
null(if your schema allows null values fortokenExp):
Modify your update object to settokenExptonullinstead 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 }); } ); });Use an invalid numeric value (like
0, if null isn't allowed):
If your schema doesn't permitnullfortokenExp, set it to a number that clearly indicates the token is expired (like0):{ 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.

