0

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"

Hopez
  • 141
  • 1
  • 9

1 Answers1

1

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 }
  })
Ashish
  • 623
  • 4
  • 10
  • The question is what query can I use to make this work because the schema shouldn't be changed @Ashish – Hopez Sep 19 '18 at 09:33
  • I don't think you can you do that as you've already defined the id field type as Number and you're expecting to match String type as well which contradicts the defined schema itself – Ashish Sep 19 '18 at 09:57