Search code examples
node.jsmongodbexpressmongoosemongoose-schema

Cast to ObjectId failed for value XXX at path XXX for model XXX


I have a simple User model with a property called bio as follows:

const userSchema = new mongoose.Schema{
   bio:{
            type: String,
            max: 150,
            default: "Welcome to my linktree!"
        }
}

I have a function to edit bio as follows:

exports.editBio = async (req, res) => {

    User.findByIdAndUpdate({_id: req.user._id}, {bio: req.body}, (err,data) => {
        if(err){
            res.json(err)
        }else{
            res.json(`Bio updated`)
        }
    })
}

However, I keep getting the error:

{
    "stringValue": "\"bio\"",
    "valueType": "string",
    "kind": "ObjectId",
    "value": "bio",
    "path": "_id",
    "reason": {},
    "name": "CastError",
    "message": "Cast to ObjectId failed for value \"bio\" (type string) at path \"_id\" for model \"User\""
}

How can I fix this?


Solution

  • This is the answer to my question :-

    The order of routes was previously:

    router.put('/:id/edit/:linkId', isLoggedIn, isAuthenticated, editLink)
    router.put('/:id/edit/bio', isLoggedIn, isAuthenticated, editBio)
    

    I first swapped the order of these routes (after searching for somewhat similar problems on the internet, this seemed to work). New order of routes:

    router.put('/:id/edit/bio', isLoggedIn, isAuthenticated, editBio)
    router.put('/:id/edit/:linkId', isLoggedIn, isAuthenticated, editLink)
    

    Then I edited my editBio function (code written below):

    exports.editBio = async (req, res) => {
    
        var input = JSON.stringify(req.body);
    
        var fields = input.split('"');
    
        var newBio = fields[3];
    
        if(newBio.length > 150){
            return res.json(`Bio cannot be more than 150 characters`)
        }else{
            try {
                await User.findByIdAndUpdate(req.user._id, { bio: newBio });
                res.json(`Bio updated`)
            }catch (err) {
                res.json(err)
            }
        }
    
    }