javascript - 带有 $or 条件的 Mongoose findOne 方法会引发错误

标签 javascript mongodb

我正在尝试从 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/

相关文章:

javascript - 如何从数组中删除重复项 - javascript

node.js - MongoDb 数据关系

MongoDB:$inc 可以增加 $addToSet 中的值吗

python - 更新mongo中的字段类型

node.js - Mongoose聚合错误: Arguments must be aggregate pipeline operators

javascript - Html 按钮无法触发与 Document.clear 同名的事件函数

javascript - Polymer 1.0 - 更改 Dom 重复中未更新的属性值

javascript - 使用 If 条件不返回函数中的值

javascript - 在页面加载前修改 location.hash

javascript - 如何在 Model.find( obj , callback) 上传播回调 promise 值?