【问题标题】:[TypeError: hex is not a function][TypeError: hex is not a function]
【发布时间】:2020-09-16 04:26:02
【问题描述】:

我的代码:

jwt.verify(token,JWT_SECRET,(err,payload)=>{
    if(err){
        res.status(401).json({error:"You must be logged in"})
    }
    const _id = payload._id
    collection_name.findById(_id)
    .then(userdata=>{
        req.user = payload
        next()
    }).catch(err=>{
        console.log(err)
    })
})

收到错误:

{ [CastError: Cast to ObjectId failed for value "5f5a5cc2b2dd9f0e50788fd8" at path "_id" for model "model_name"]

消息格式:未定义, stringValue: '"5f5a5cc2b2dd9f0e50788fd8"', 种类:'ObjectId', 值:'5f5a5cc2b2dd9f0e50788fd8', 路径:'_id',
原因:[TypeError: hex is not a function] }

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您正在尝试在 MongoDB(_id) 中搜索字符串 id (payload._id),

    您需要在搜索之前将字符串 id 转换为对象 id

    const mongoose = require('mongoose');
    const _id = mongoose.Types.ObjectId(payload._id)
    

    【讨论】:

    • 我仍然收到 hex is not a function 的错误
    • 你使用的是mongo驱动还是mongoose?
    • 我正在使用猫鼬
    • TypeError: hex is not a function
    • 仍然只有这个