Mongoose's findOne method with $or condition throws an errror

时间:2018-09-19 08:25:58

标签: javascript mongodb

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"

1 个答案:

答案 0 :(得分:1)

您定义的学生模式说id类型为Number,因此在运行查询时,您将字符串值作为id提供,因此您应在模式中使用String而不是Number作为id作为id,如下所示:

const Student = new Schema({
      id: String,
      studentId: String,
      firstName: String
      lastName: String,
      .....
  })

  let studentInfo = await Student.findOne({
         $or: [{"studentId": `${idValue}` }, { "id": idValue }
  })