未处理的承诺拒绝警告投射错误

时间:2018-02-27 10:08:55

标签: node.js mongodb mongoose

我使用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的值正在获得正确的值,即' testing',数据库中的用户名称' m从输入字段输入。

(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 })

并输入搜索框' testing'或

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"

由于

2 个答案:

答案 0 :(得分:1)

试试这个

ListenerRegistration registration = query.addSnapshotListener(
    new EventListener<QuerySnapshot>() {
        // ...
    });
//... Stop listening to changes
registration.remove();

答案 1 :(得分:1)

尝试以下方法:

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))