如果没有mongoose查找查询 - 没有结果

时间:2015-05-06 10:11:40

标签: node.js express mongoose

我正在开发一个使用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

1 个答案:

答案 0 :(得分:0)

如果搜索并且没有结果,则callign将为空数组。通过测试检查(callsign.length === 0)。如果它返回true则没有结果。

if(err){
  //handle error in mongo
}
if(callsign.length === 0){
  //handle search with no reults
}
else {
  //handle search with results
}