【发布时间】:2014-06-04 23:56:01
【问题描述】:
这发生在 node.js 应用程序上。
我正在尝试查看 MongoDB 中是否存在 hrefs 数组中的食谱 URL 之一。以下代码在第一次运行时有效,但在 30 秒后再次运行时失败(setInterval)。
第一次成功返回数组中每个 URL 的 yes 或 no:
yes
no
yes
yes
yes
yes
三十秒后,当它第二次运行时:
ERROR connecting to: mongodb://<the url here>. Error: failed to connect to [<the url here]]
ERROR connecting to: mongodb://<the url here>. Error: failed to connect to [<the url here]]
ERROR connecting to: mongodb://<the url here>. Error: failed to connect to [<the url here]]
ERROR connecting to: mongodb://<the url here>. Error: failed to connect to [<the url here]]
ERROR connecting to: mongodb://<the url here>. Error: failed to connect to [<the url here]]
代码:
var mongoDB;
function connectToDb(done){
mongo.connect(uristring, options, function (err, db) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connected to: ' + uristring);
mongoDb = db;
done();
}
});
}
function checkHREFS(recipes) {
var recipeCollection = mongoDb.collection('recipeURL');
recipefCollection.findOne({
'recipe_url': { $in: recipes }
}, function (err, recipe) {
if (err) {
console.log('ERROR:' + err);
} else if (!href) {
console.log('no');
} else {
console.log('yes');
return true;
}
});
}
connectToDb(function(){
checkHREFS(hrefs);
});
更新:这没有帮助,并且 if(mongDB) 中的 console.log 永远不会被调用。
var mongoDB;
function connectToDb(done){
if(mongoDB) { console.log('already connected'); return done(); }
mongo.connect(uristring, options, function (err, db) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connected to: ' + uristring);
mongoDb = db;
done();
}
});
}
我得到一个巨大的错误列表,它们在以下两个错误之间切换:
ERROR connecting to: <url here>. Error: failed to connect to [<number here>.mongolab.com:<port here>]
ERROR connecting to: <url here>. Error: No valid replicaset instance servers found
我在同一个文件中的另一个功能可以正常工作:
connectToDb(function(){
recipesToDB(recipes);
});
function recipesToDB(recipes) {
mongoDb.createCollection('recipes', function(err, collection) {});
var recipeCollection = mongoDb.collection('recipes');
recipeCollection.insert(recipes, {continueOnError: true}, function(err, result) {
if (err) {
console.log('ERROR:' + err);
} else {
console.log('*******************************************');
console.log('********Succeeded inserted recipes********');
console.log('*******************************************');
}
});
}
【问题讨论】:
-
你不应该在每次需要调用
checkHREFS时都打开一个新的连接池;您应该在启动期间为应用程序打开一个池。 -
您可以在 connectToDb 的顶部添加一行,其作用类似于:
if(mongoDB) { return done(); } -
@PeterVC,根据您的建议更新了原始帖子。仍然没有运气:(。
-
@JohnnyHK,我该怎么做?
-
这很奇怪,因为我在计时器上插入数据的另一个函数工作正常......但是使用 findOne 和这个数组在运行一次后会中断。
标签: javascript node.js mongodb database