For a project, I need to switch between some MongoDB databases for doing some queries.
I found some exemple like that one : Mongoose and multiple database in single node.js project
His answer is perfectly working but now I'm trying to do it in a loop and unfortunally it's not work, I get this error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: failed to connect to [localhost:27017]
at null.<anonymous> (/home/user/test_many_db_mongodb/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:549:74)
at EventEmitter.emit (events.js:106:17)
at null.<anonymous> (/home/user/test_many_db_mongodb/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:150:15)
at EventEmitter.emit (events.js:98:17)
at Socket.<anonymous> (/home/user/test_many_db_mongodb/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:533:10)
at Socket.EventEmitter.emit (events.js:95:17)
at net.js:440:14
at process._tickCallback (node.js:419:13)
And I don't understand why I get this error, if the example in the link above work my code should too:
var mongoose = require('mongoose');
for (var i = 0; i != 1000; i++) {
var conn = mongoose.createConnection('mongodb://localhost/test' + i);
conn.on('connected', function() {
console.log('Mongoose connected to database');
var Model = conn.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in test database' }
}));
var newModelA = new Model();
newModelA.save(function(err) {
if (err)
console.log(err);
console.log('save A');
});
});
}
Thanks for your help.