【发布时间】: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"
谢谢
【问题讨论】: