javascript - 检查采样猫鼬的结果
问题描述
在研究中,我一度陷入困境。尝试使用 Mongoose 检查 MongoDB 数据库集合文档中是否存在值。我有一个单独的函数,它使用 findOne 搜索数据库条目。如果我们从代码中删除所有不必要的内容,它看起来像这样:
const checkUserExist = async (userName) => {
return await userModel.findOne ({userName});
};
const validateRegistrationData = (inputData) => {
const {userName} = inputData;
const userExist = checkUserExist (userName);
if (userExist) {
console.log ('User found')
}
else {
console.log ('User not found')
}
};
问题是在这种情况下它总是返回 true。
我尝试了更多选择:
if (! userName) {
}
if (userName === null) {
}
if (userName! == null) {
}
if (userName === undefined) {
}
if (userName! == undefined) {
}
文件模型:
const userSchema = new Schema (
{
userName: {type: String, unique: true, required: true},
name: {type: String, required: true},
email: {type: String, unique: true, required: true},
encryptedPassword: {type: String, required: true},
},
);
这显然是新手错误,但我在网络上没有找到任何明确的信息。
解决方案
这是因为您没有等待该checkUserExist()
方法。因为该方法返回一个承诺,if
所以您的陈述将始终为真。如果您转换validateRegistrationData()
为一种async
方法并且对它await
的调用checkUserExist()
应该按预期工作。
像这样的东西:
const validateRegistrationData = async (inputData) => {
const {userName} = inputData;
const userExist = await checkUserExist(userName);
if (userExist) {
console.log ('User found')
} else {
console.log ('User not found')
}
};
推荐阅读
- python - 在 Python 中查找所有行的单元格之间的相关性
- laravel - 从子目录 Admin 访问 public_html 中的图像 - Laravel
- variables - 如何在emacs-lisp中将变量约束为正?
- php - 在 if/else 的 where 更新子句中使用 select 语句的值
- ruby-on-rails - Rails 5.2、AWS S3 和 ActiveStorage 无法自动加载常量 ActiveStorage::Blob::Analyzable 错误
- asciidoctor - 渲染pdf时如何更改页码的位置?
- c++ - 在 Linux 上部署 Qt 应用程序
- schema.org - 表列表的带有 QuantitativeValue 的 ItemList
- c# - 无法在布局 Razor 视图文件中使用 @Html.React
- python - 仅当状态为真时,如何在一定时间后在 python 中使用函数?