Zaid Humayun Zaid Humayun - 3 months ago 11
Node.js Question

Why is my callback function not being executed in the db.collection.findOne method below

var express = require('express');
var GoogleUrl = require('google-url');
var favicon = require('serve-favicon');
var mongo = require('mongodb').MongoClient;
var app = express();
var db;
var googleUrl = new GoogleUrl({key: 'AIzaSyB5i1sdnt6HwzrvsPTBu0FbPiUZrM_BCsk'});
var PORT = 8080;

mongo.connect('mongodb://localhost:27017/url-shortener', function(err, newDb){
if(err){
throw new Error('Database failed to connect');
} else{
console.log('Successfully connected to MongoDB on port 27017');
}
db=newDb;
db.createCollection('sites', {
autoIndexID: true
});
db.close();
});

app.use(favicon(__dirname+'/public/favicon.ico'));

app.get('/new/*', function(req, res){
console.log('This is the url: '+req.params[0]);
googleUrl.shorten(req.params[0], function(err, shortUrl){
if(err){
console.log(err);
}else{
console.log(shortUrl);
}
check_db(req.params[0], shortUrl, db);
});
});


app.listen(process.env.PORT, function(){
console.log('Express listening on: '+PORT);
});

function check_db(longUrl, shortUrl, db){

db.collection('sites').findOne({
'longUrl': longUrl,
'shortUrl': shortUrl
}, function(err, result){ //callback function is here but not logging any statements from within.
console.log('entering callback');
if(err){
console.log(err);
}if(result){
console.log('This site already exists on the database');
}else{
console.log('This site does not exist on the database');
}
});
}


The callback function for
db.collection.findOne
is not returning any errors, but the code runs and does not execute any of the log statements from within that callback function.

Code not returning any errors either. Unsure of how to proceed debugging this. Why is the callback function not generating any log statements?

Answer

You're closing database before running the query, remove db.close() line from mongo.connect callback and it should work fine.