在學習中,我一度陷入困境。嘗試使用 Mongoose 檢查 MongoDB db 集合檔案中是否存在值。我有一個單獨的函式,可以使用 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},
},
);
這顯然是一個新手錯誤,但我在網路上沒有找到任何明確的資訊。
uj5u.com熱心網友回復:
這是因為你沒有在等待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')
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/344687.html
標籤:javascript 节点.js MongoDB 猫鼬
