Reputation: 472
I am facing a weird issue when working with multiple connections in mongoose 4.x.
After following the instructions in their documentation, I created two connections for the two databases I need to use (db1.js
and db2.js
).
When I try to fetch records in both databases, for some reason one of the find()
calls returns no data. For instance, considering the database below, User1.find({})
should return 3 records (which is correct), and User2.find({})
should return 2 (which doesn't happen).
Any idea on what would be the issue is much appreciated!
Database dump to reproduce
use db1;
db.createUser({
user: "admin",
pwd: "admin",
roles: [
{ role: "dbAdmin", db: "db1" },
{ role: "dbAdmin", db: "db2" },
]
});
db.user1.insert({ "name": "Isa1" });
db.user1.insert({ "name": "Joe1" });
db.user1.insert({ "name": "Doe1" });
use db2;
db.createUser({
user: "admin",
pwd: "admin",
roles: [
{ role: "dbAdmin", db: "db1" },
{ role: "dbAdmin", db: "db2" },
]
});
db.user2.insert({ "name": "Isa2" });
db.user2.insert({ "name": "Doe2" });
db1.js
const Mongoose = require("mongoose");
const RSVP = require("rsvp");
Mongoose.Promise = RSVP.Promise;
let options = {
useMongoClient: true,
autoReconnect: true,
keepAlive: 3000000,
connectTimeoutMS: 300000
};
let schema = new Mongoose.Schema({ name: String });
const conn1 = Mongoose.connect('mongodb://admin:admin@localhost/db1', options);
module.exports = conn1.model('User1', schema);
db2.js
const Mongoose = require("mongoose");
const RSVP = require("rsvp");
Mongoose.Promise = RSVP.Promise;
let options = {
useMongoClient: true,
autoReconnect: true,
keepAlive: 3000000,
connectTimeoutMS: 300000
};
const conn2 = Mongoose.connect('mongodb://admin:admin@localhost/db2', options);
let schema = new Mongoose.Schema({ name: String });
module.exports = conn2.model('User2', schema);
index.js
const Mongoose = require("mongoose");
const RSVP = require("rsvp");
const User1 = require("./db1");
const User2 = require("./db2");
User1.find({})
.then(res => {
console.log(res.length); //print 3
return User2.find({});
})
.then(res => {
console.log(res.length); //print 0 (should be 2) <----- ERROR
return User1.find({});
})
.then(res => {
console.log(res.length); //print 3
return User2.find({});
})
.then(res => {
console.log(res.length); //print 2
})
.catch(err => {
console.log(err);
});
Upvotes: 0
Views: 38