繁体   English   中英

尝试在下面的代码中访问db.collection时,为什么会得到未定义的信息?

[英]Why am I getting an undefined when I try to access db.collection in the code 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: '********'});
var PORT = 8080;


mongo.connect('mongodb://localhost:27017/url-shortener', function(err, db){
   if(err){
       throw new Error('Database failed to connect');
   } else{
       console.log('Successfully connected to MongoDB on port 27017');
   }
   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(PORT, function(){
    console.log('Express listening on: '+PORT);
});

//当我尝试在此处调用db.collection方法时,收到一条错误语句,提示TypeError:无法读取未定义的属性“ collection”。

function check_db(longUrl, shortUrl, db){
    db.collection('sites').findOne({
        'longUrl': longUrl, 
        'shortUrl': shortUrl
    }, function(err, result){
        if(err){
            throw new Error(err);
        }if(result){
            console.log('This site already exists on the database');
        }else{
            console.log('This site does not exist on the database');
        }
    });
}

我已经确保全局声明我的db变量,甚至将其传递给check_db函数来确保。

以下是完整的错误声明

TypeError:无法在/ home的/home/ubuntu/workspace/urlshortener/server.js:35:8的check_db(/home/ubuntu/workspace/urlshortener/server.js:45:7)处读取未定义的属性'collection' /ubuntu/workspace/urlshortener/node_modules/google-url/lib/google.js:18:7 at Instant._onImmediate(/home/ubuntu/workspace/urlshortener/node_modules/google-url/lib/google.js:163: 11)在processImmediate [as _immediateCallback](timers.js:383:17)

您的数据库是未定义的。 您必须将其分配给您在connect回调中创建的数据库。

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; // ADD THIS
   db.createCollection('sites', {
      autoIndexID: true 
   });
   // db.close();
});

编辑:

正如@notionquest的答案所指出的,您还必须保持连接打开,直到您的请求完成。

您在以下行上获得mongo连接:-

mongo.connect('mongodb://localhost:27017/url-shortener', function(err, db){

然后关闭其中的连接:

db.close();

请评论此结束声明,然后尝试。 我认为应该可以。

如果您想使用相同的连接(这是一种很好的做法),请不要关闭该连接。 您可以在最后关闭连接。

暂无
暂无

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

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