gpt4 book ai didi

javascript - 当我尝试在下面的代码中访问 db.collection 时,为什么会出现未定义的情况?

转载 作者:行者123 更新时间:2023-12-02 14:13:25 24 4
gpt4 key购买 nike

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

//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)

最佳答案

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

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

关于javascript - 当我尝试在下面的代码中访问 db.collection 时,为什么会出现未定义的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39264389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com