猫鼬只连接到一个数据库,而不是两个

时间:2019-04-19 04:37:36

标签: javascript express mongoose

我正在用JS开发一个小项目,想访问2个不同的猫鼬数据库。似乎只有一个数据库正在访问...

这是我在app.js中的代码:

mongoose.connect('mongodb://someOtherDb', { useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection;
connection.on('open',()=>{
    console.log(" database connected")
})
connection.on('error',()=>{
    console.log("error in connecting to database")
})

mongoose.connect('mongodb://localhost:27017/users', { useNewUrlParser: true, useCreateIndex: true });
const userDb = mongoose.connection;

// on mongo error
userDb.on('error', console.error.bind(console, 'connection error:'));

// sessions for logins
app.use(session({
  secret: 'top secret!',
  saveUninitialized: false,
  resave: true,
  store: new MongoStore({
    mongooseConnection: userDb
  })
}));

mongoose.connect部分有问题吗,如何将userDb和connection设置为等于mongoose.connection?

谢谢!

1 个答案:

答案 0 :(得分:0)

通过连接池的猫鼬处理连接 http://mongoosejs.com/docs/connections.html

您可以使用server: {poolSize: 5}选项增加/减少池(并行连接的数量)

如果需要连接到其他数据库,请点击此处 Mongoose and multiple database in single node.js project

多个连接的示例:

var mongoose = require('mongoose')
var conn1 = mongoose.createConnection('mongodb://someOtherDb');
var conn2 = mongoose.createConnection('mongodb://localhost:27017/users');
var Schema = new mongoose.Schema({})
var model1 = conn1.model('collection1', Schema);
var model2 = conn2.model('collection2', Schema);
model1.find({}, function() {
   console.log("datas found 1");
});
model2.find({}, function() {
   console.log("datas found 2");
});