【问题标题】:after nodejs update i get this error: Cast to ObjectId failed for value "600204c674086624b9de76e2" at path "classId" for model "Message"nodejs更新后我收到此错误:Cast to ObjectId failed for value "600204c674086624b9de76e2" at path "classId" for model "Message"
【发布时间】:2023-04-02 04:27:01
【问题描述】:

这是我的代码:

async function allMessage(roomId){
     await Message.find({ classId: roomId }).sort({ date: -1 }).limit(4)
    .populate('userId', 'name')// just select name
    .exec(function(allMessage){

        console.log(allMessage);
    })
}

这是我的模型结构:

userId:{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
},

classId:{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Classroom'
},

message:{
    type: String,
    required: true
},

date:{
    type: Date,
    default: Date.now
}

但我收到此错误:Cast to ObjectId failed for value "600204c674086624b9de76e2" at path "classId" for model "Message"

我尝试使用以下代码将 roomId 更改为 ObjectId:

mongoose.Types.ObjectId(roomId)

但我收到此错误:传入的参数必须是 12 个字节的单个字符串或 24 个十六进制字符的字符串

在更新 nodejs 之前它工作正常。我现在很困惑。我该怎么办?

【问题讨论】:

  • 试试这个语法 new ObjectID (id) 在 mongo 中找到类似 Message.find({ classId: new ObjectID(roomId) }) 的记录。
  • 尝试在你得到的字符串 id 上使用 trim() 然后通过。
  • 干得好@NamitPiriya roomId.trim() 工作!!

标签: node.js mongoose mongoose-schema


【解决方案1】:

尝试在你得到的字符串 id 上使用 trim(),然后在查询中传递它

【讨论】:

    猜你喜欢
    • 2017-08-14
    • 2017-02-06
    • 2020-12-10
    • 2013-02-03
    • 2022-06-14
    • 2021-04-20
    • 2017-03-23
    • 2019-09-03
    相关资源
    最近更新 更多