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

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



//When I try to call my db.collection method here, I get an error
statement saying that TypeError: Cannot read property 'collection' of
undefined.


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



I have made sure to declare my db variable globally and I even passed
it to the check_db function to make sure.

Following is the error statement in full

TypeError: Cannot read property 'collection' of undefined
at check_db (/home/ubuntu/workspace/urlshortener/server.js:45:7)
at /home/ubuntu/workspace/urlshortener/server.js:35:8
at /home/ubuntu/workspace/urlshortener/node_modules/google-url/lib/google.js:18:7
at Immediate._onImmediate (/home/ubuntu/workspace/urlshortener/node_modules/google-url/lib/google.js:163:11)
at processImmediate [as _immediateCallback] (timers.js:383:17)

Answer

Your db is undefined. You have to assign it to the created db in your connect callback.

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

EDIT:

as pointed out by the answer of @notionquest, you also have to keep the connection open until your requests are done.

Comments