您好,有没有办法用 mongoose 切换数据库?
我想我可以这样做:
mongoose.disconnect();
mongoose.connect('localhost',db);
但它不起作用我收到此错误:
Error: Trying to open unclosed connection.
不知道是不是因为是异步的
正如已经说过的,你可以使用useDb
功能 :
示例代码:
async function myDbConnection() {
const url = 'mongodb+srv://username:[email protected]/test?retryWrites=true&w=majority';
try {
await mongoose.connect(url, { useNewUrlParser: true });
console.log('Connected Successfully')
// Here from above url you've already got connected to test DB,
So let's make a switch as needed.
mongoose.connection.useDb('myDB'); // Switching happens here..
/**
* Do some DB transaction with mongoose models as by now models has already been registered to created DB connection
*/
} catch (error) {
console.log('Error connecting to DB ::', error);
}
}
或者,如果您想创建一个全新的连接,那么您必须尝试mongoose.createConnection()
。仅供参考,以防万一mongoDB
您将使用的驱动程序::
mongodb.MongoClient.connect(mongourl, function(err, primaryDB) {
// open another database over the same connection
const secondaryDB = primaryDB.db(SECONDARY_DATABASE_NAME);
// now you can use both `database` and `database2`
...
});
Ref : 猫鼬多个不同的连接, 猫鼬 useDb(), mongoDB驱动程序切换连接
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)