Node.js 未处理的承诺拒绝警告强制转换错误
我在使用mongoose和mongodb时遇到了一个错误,由于cast错误,我无法在数据库中找到东西 我有一个用户模式Node.js 未处理的承诺拒绝警告强制转换错误,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我在使用mongoose和mongodb时遇到了一个错误,由于cast错误,我无法在数据库中找到东西 我有一个用户模式 const schema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, name: { type: String, min: 1, required: true } }); export default mongoose.model('user',schema); 在另一个文件中,我
const schema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, min: 1, required: true }
});
export default mongoose.model('user',schema);
在另一个文件中,我有一个用户id从输入字段获取输入的文件
User.findOne({ name: user_id })
.then(user => {
if(user) {
console.log("found user");
console.log(user);
} else {
console.log("user not found");
}
})
});
问题是我得到了cast错误,在错误中我可以看到user_id的值得到了正确的值,即“testing”,我从输入字段输入数据库中的用户名
(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"
谢谢你试试这个
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");)
试试这个
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");)
请尝试以下操作:
User.findById('5a952adf327915e625aa0fed')
.then(user => console.log(user)) // user can be undefined
.catch(e => console.error(e))
或
请尝试以下操作:
User.findById('5a952adf327915e625aa0fed')
.then(user => console.log(user)) // user can be undefined
.catch(e => console.error(e))
或
如果我将实际id放入findById查询中,它会起作用,但如果我传入它,则不会起作用。这与我当时传递数据的方式有关吗?从错误日志中可以看出,您尝试使用对象调用
findById
。尝试使用字符串调用。是的,这很有效。谢谢,我假设我在字符串中传递的是什么,即user\u id,但它是用户的实际对象,而不是值。更改为findById(user\u id.user\u id)
如果我将实际id放入findById查询中,它会起作用,但如果我传入它,则不会起作用,这与我当时传递数据的方式有关吗?据我从错误日志中看到的,您尝试使用对象调用findById
。尝试使用字符串调用。是的,这很有效。谢谢,我假设我在字符串中传递的是什么,即user\u id,但它是用户的实际对象,而不是值。更改为findById(用户id.user\u id)