为什么我的回调函数没有在下面的db.collection.findOne方法中执行

时间:2016-09-01 11:09:11

标签: javascript node.js express

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');
        }
    });
}

db.collection.findOne的回调函数没有返回任何错误,但代码运行并且不执行该回调函数中的任何日志语句。

代码也没有返回任何错误。不确定如何继续调试。为什么回调函数不生成任何日志语句?

1 个答案:

答案 0 :(得分:3)

您在运行查询之前关闭数据库,从db.close()回调中移除mongo.connect行,它应该可以正常工作。