Reputation: 141
I'm trying to retrieve data from mongodb. Currently I have a file from which I first get the Id with which I want to search mongodb. The query throws an error when the first condition is not met and tries to search using the second condition. How do I tackle this please?.
I have checked this but the case is different here
Example of value retrieved from file
let idValue = student_id ? student_id : id
idValue = stu_367
Sample db structure
const Student = new Schema({
id: Number,
studentId: String,
firstName: String
lastName: String,
.....
})
let studentInfo = await Student.findOne({
$or: [{"studentId": `${idValue}` }, { "id": idValue }
})
I get this error Cast to number failed for value "stu_367" at path "id" for model "Student"
Upvotes: 0
Views: 114
Reputation: 643
Student schema you defined says id type is Number so while running your query you're providing string value as id so you should use type String instead of Number for id in schema as follows:
const Student = new Schema({
id: String,
studentId: String,
firstName: String
lastName: String,
.....
})
let studentInfo = await Student.findOne({
$or: [{"studentId": `${idValue}` }, { "id": idValue }
})
Upvotes: 1