我正在尝试从 mongodb 检索数据。目前我有一个文件,我首先从中获取要搜索 mongodb 的 Id。当不满足第一个条件时,查询会抛出错误,并尝试使用第二个条件进行搜索。请问我该如何解决这个问题?
我查过this但这里的情况有所不同
从文件中检索值的示例
let idValue = student_id ? student_id : id
idValue = stu_367
示例数据库结构
const Student = new Schema({
id: Number,
studentId: String,
firstName: String
lastName: String,
.....
})
let studentInfo = await Student.findOne({
$or: [{"studentId": `${idValue}` }, { "id": idValue }
})
我收到此错误对于模型“Student”的路径“id”处的值“stu_367”,转换为数字失败
最佳答案
您定义的学生模式表示 id 类型是 Number,因此在运行查询时,您提供字符串值作为 id,因此您应该在模式中使用 String 类型而不是 Number 类型作为 id,如下所示:
const Student = new Schema({
id: String,
studentId: String,
firstName: String
lastName: String,
.....
})
let studentInfo = await Student.findOne({
$or: [{"studentId": `${idValue}` }, { "id": idValue }
})
关于javascript - 带有 $or 条件的 Mongoose findOne 方法会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52401398/