【问题标题】:Why am I getting an undefined when I try to access db.collection in the code below?当我尝试在下面的代码中访问 db.collection 时,为什么会出现未定义?
【发布时间】:2016-09-01 06:45:06
【问题描述】:
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: Cannot read property 'collection' of 未定义。

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:无法读取未定义的属性“集合” 在 check_db (/home/ubuntu/workspace/urlshortener/server.js:45:7) 在 /home/ubuntu/workspace/urlshortener/server.js:35:8 在 /home/ubuntu/workspace/urlshortener/node_modules/google-url/lib/google.js:18:7 在 Immediate._onImmediate (/home/ubuntu/workspace/urlshortener/node_modules/google-url/lib/google.js:163:11) 在 processImmediate [as _immediateCallback] (timers.js:383:17)

【问题讨论】:

  • 我看不到你在哪里初始化变量db
  • db在mongo shell中是全局变量,在node js中不是。
  • @Mr.7 - 我在程序的第六行初始化它。
  • @notionquest - 你是什么意思?它怎么可能是 mongo shell 中的全局变量,而不是节点 js 中的全局变量
  • 不要将apikeys放在共享代码中????‍♂️

标签: javascript node.js mongodb express


【解决方案1】:

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

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 的回答所指出的,您还必须保持连接打开,直到您的请求完成。

【讨论】:

  • 所以你的解决方案奏效了!谢谢!但是,我现在在我的 check_db 函数中有一个不同的问题,其中应用程序没有记录控制台语句。它进入 findOne 方法,但不进入回调。我试过通过调试器运行它,但没有运气!
【解决方案2】:

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

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

然后关闭里面的连接:-

db.close();

请评论此关闭声明并尝试。我认为它应该有效。

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

【讨论】:

    猜你喜欢
    • 2013-01-03
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多