简体   繁体   中英

node js callback function

I am new to nodeJs. In my code I have a asynchronous function for finding records from 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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