gpt4 book ai didi

node.js - 使用 mongoose 切换数据库

转载 作者:太空宇宙 更新时间:2023-11-03 23:09:58 26 4
gpt4 key购买 nike

嗨,有没有办法用 Mongoose 切换数据库?我想我可以这样做:

mongoose.disconnect();
mongoose.connect('localhost',db);

但它不起作用我收到此错误:

Error: Trying to open unclosed connection.

不知道是不是因为是异步的

最佳答案

如前所述,您可以使用 useDb 函数来完成此操作:

示例代码:

async function myDbConnection() {

const url = 'mongodb+srv://username:password@cluster0-pauvx.mongodb.net/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`
...
});

引用: mongoose multiple different connections , mongoose useDb() , mongoDB driver switch connections

关于node.js - 使用 mongoose 切换数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17862541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com