【问题标题】:Unhandled Promise Rejection Warning Cast error未处理的 Promise Rejection 警告 Cast 错误
【发布时间】:2018-08-06 22:41:59
【问题描述】:

我在使用 mongoose 和 mongodb 时遇到了一个错误,由于转换错误,我无法在数据库中找到东西。

我有一个用户架构

const schema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: { type: String, min: 1, required: true }
});

export default mongoose.model('user',schema);

在另一个文件中,我有这个 user_id 从输入字段获取输入的地方

User.findOne({ name: user_id })
  .then(user => {
    if(user) {
      console.log("found user");
      console.log(user);
    } else {
      console.log("user not found");
    }
  })
});

问题是我得到了转换错误,在错误中我也可以看到 user_id 的值得到了正确的值,即“测试”,我从输入字段输入的数据库中的用户名。

(node:1127) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): CastError: Cast to string failed for value "{ user_id: 'testing' }" at path "name" for model "user"

如果我将第一行代码更改为

User.findOne({})

查询找到一个并打印出来

{ _id: 5a952b07327915e625aa0fee, name: 'testing' }

但如果我将代码更改为任一

User.findOne({ name: user_id })

并在搜索框中输入“测试”,或

User.findOne({ _id: user_id })

然后输入 id '5a952b07327915e625aa0fee',我得到了错误。使用时我也遇到类似的错误

User.findById(user_id)
node:1166) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): CastError: Cast to ObjectId failed for value "{ user_id: '5a952adf327915e625aa0fed' }" at path "_id" for model "user"

谢谢

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    试试这个

    User.findOne({ name: user_id })
      .then(user => {
        if(user) {
          console.log("found user");
          console.log(user);
        } else {
          console.log("user not found");
        }
    }).catch(err => console.log("something went wrong");)
    

    【讨论】:

      【解决方案2】:

      尝试以下方法:

      User.findById('5a952adf327915e625aa0fed')
          .then(user => console.log(user))  // user can be undefined
          .catch(e => console.error(e))
      

      User.findOne({name: 'testing'})
          .then(user => console.log(user))  // user can be undefined
          .catch(e => console.error(e))
      

      【讨论】:

      • 如果我将实际的 id 放在 findById 查询中,但如果我将它传递进去,它会起作用,这与我传递数据的方式有关吗?
      • 据我从您的错误日志中看到,您尝试使用对象调用 findById。尝试使用String 调用。
      • 是的,谢谢,我假设我在字符串中传递了什么,即 user_id 但它是用户的实际对象而不是值。改为findById(user_id.user_id)
      猜你喜欢
      • 2020-09-13
      • 2021-06-21
      • 2018-02-13
      • 1970-01-01
      • 2020-08-30
      • 2020-07-27
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多