简体   繁体   English

节点js回调函数

[英]node js callback function

I am new to nodeJs. 我是nodeJs的新手。 In my code I have a asynchronous function for finding records from mongoDB. 在我的代码中,我有一个异步函数,用于从mongoDB中查找记录。

var restify = require('restify');
var mongojs = require('mongojs');

var ip_addr = '127.0.0.1';
var port    =  '8080';

var server = restify.createServer({
    name : "signapp"
});

server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());

var connection_string = '127.0.0.1:27017/signapp';
var db = mongojs(connection_string, ['signapp']);

var docDetails = db.collection("SIGN_DOCUMENT_DETAILS");

var PATH = '/documents'
server.post({path : PATH  + '/:search', version: '0.0.1'}, searchDoc);

function searchDoc(req, res, next)
{
 var criteria = {};
 criteria.DOC_NAME = req.params.DOC_NAME;

  if (criteria.DOC_NAME !== '' || criteria.DOC_NAME !== null)
  {
    docDetails.find({DOC_NAME : criteria.DOC_NAME}, function(err, users){
    if( err || !users){
       console.log("No record found");
    }
    else {
        console.log('record found');
    }
    });
  }

}

In my request I pass a string parameter. 在我的请求中,我传递了一个字符串参数。 I am getting 'record found' response in my console when the condition is matched. 当条件匹配时,我在控制台中收到“找到记录”响应。 But the problem is I am getting response in console as 'record found' even when the find condition fails. 但是问题是,即使查找条件失败,我也会在控制台中以“找到记录”获得响应。 I tried a lot ti find a solution but failed. 我试图找到解决方案很多,但都失败了。 Please tell me where I went wrong in my code. 请告诉我代码出错的地方。 A solution for this bug will be greatly appreciated. 此错误的解决方案将不胜感激。 Thanks in advance. 提前致谢。

change your condition like 改变你的状况

if( err){
   console.log("An error occurred");
} else if(!users || users.length==0) {
   console.log("No results found");
} else {
   console.log('record found');
}

You need to add a condition to check if the returned array was empty. 您需要添加条件来检查返回的数组是否为空。

note : 注意 :

javascript empty array seems to be true and false at the same time gives a proper explanation on why u should not use if(!users) to check if the array was empty. javascript空数组似乎同时是对还是错,这说明了为什么您不应该使用if(!users)检查数组是否为空的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM