【问题标题】:Cast to ObjectId failed for value XXX at path XXX for model XXX模型 XXX 的路径 XXX 处的值 XXX 转换为 ObjectId 失败
【发布时间】:2021-10-17 04:50:09
【问题描述】:

我有一个简单的用户模型,其属性名为bio,如下所示:

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

我有一个编辑简历功能如下:

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`)
        }
    })
}

但是,我不断收到错误消息:

{
    "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\""
}

我该如何解决这个问题?

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-schema


    【解决方案1】:

    这是我问题的答案:-

    以前的路线顺序是:

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

    我首先交换了这些路线的顺序(在互联网上搜索了一些类似的问题后,这似乎有效)。新的路线顺序:

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

    然后我编辑了我的editBio函数(代码写在下面):

    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)
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-11
      • 2020-05-20
      • 2021-02-21
      • 2015-11-07
      • 2023-03-28
      • 2017-05-23
      • 2020-04-18
      • 2020-11-19
      • 2021-05-12
      相关资源
      最近更新 更多