[英]If else mongoose find query - no results
我正在開發一個使用Mongoose進行數據庫調用的node.js / express / passport應用程序。
我目前正在嘗試檢查查詢中是否有任何結果,但是不管我嘗試什么,它仍然會說有結果-即使沒有!
我的代碼:
User.find({'callsign' : new RegExp('^'+search+'$', "i")}, function(err, callsign){
if(err)
{
console.log('No user found'+err);
req.flash('message','Sorry, something went wrong. Try again.');
res.render('callSearchResults'),{
message: req.flash('message'),
title: 'Sorry, no results'
}
}
if(callsign){
console.log('Callsign:'+callsign);
res.render('callSearchResults',{
call: callsign,
title: 'You searched for '+search,
query: search
});
}else{
console.log('No entries found'+search);
}
});
我嘗試使用以下方法檢查結果集是否為空,但它始終忽略它進行的任何操作。
if(callsign==[]){
console.log("No results"); // Doesn't output anything in console
}
if(callsign==null){
console.log("No results"); // Doesn't output anything in console
}
if(!callsign.length){
console.log("No results"); // Doesn't output anything in console
}
但是,控制台顯示:
Callsign:
POST /search 200 902ms - 1.51kb
如果您搜索但沒有結果,則呼號將為空數組。 通過測試進行檢查(callsign.length === 0)。 如果返回true,則沒有結果。
if(err){
//handle error in mongo
}
if(callsign.length === 0){
//handle search with no reults
}
else {
//handle search with results
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.