在 Node.js 中,我创建了一个 API 来根据客户的手机号码或电子邮件检查客户是否存在。但是,当我传递数据库中不存在的值时,它仍然显示“成功”响应。如果找不到客户,我该如何编写返回适当消息的逻辑?
Node js - 模型文件代码--
export async function existing_customer_check(data){
const email = data.email;
const mobile = data.mobile;
const register_customer_check_query = `SELECT email , mobile FROM users WHERE email = ? || mobile = ? `;
try{
const result = await new Promise((resolve,reject)=>{
pool.query(register_customer_check_query,[email,mobile],(error,result,fields)=>{
if(error){
reject(error);
}
else{
resolve(result);
}
})
})
return result;
}catch(error){
throw new Error(error.message);
}
}
控制器文件
export async function existing_customer_check(data){
const email = data.email;
const mobile = data.mobile;
const register_customer_check_query = `SELECT email , mobile FROM users WHERE email = ? || mobile = ? `;
try{
const result = await new Promise((resolve,reject)=>{
pool.query(register_customer_check_query,[email,mobile],(error,result,fields)=>{
if(error){
reject(error);
}
else{
resolve(result);
}
})
})
return result;
}catch(error){
throw new Error(error.message);
}
}
如果数据库中没有您要查找的条件,则不会返回错误。相反,它将返回一个空值。例如,它将返回一个空数组。您需要检查其占用情况并创建错误(例如未找到记录)并将其传递。如果返回空数组,可以按如下方式检查:
if (result.length === 0) {
throw new Error('No customer found!);
}