首页 > 解决方案 > 检查采样猫鼬的结果

问题描述

在研究中,我一度陷入困境。尝试使用 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},
},
);

这显然是新手错误,但我在网络上没有找到任何明确的信息。

标签: javascriptnode.jsmongodbmongoose

解决方案


这是因为您没有等待该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')
    }
};

推荐阅读