gpt4 book ai didi

javascript - Mongoose 切换多个连接

转载 作者:可可西里 更新时间:2023-11-01 09:54:03 24 4
gpt4 key购买 nike

我正在使用 Node.Js 8.6 和 Mongoose 4.11,并且有多个数据库连接。数据库连接是通过 mongoose.createConnection 建立的。我发现 mongoose 对象具有 connections 属性(数组),我可以在其中看到已建立的连接。我的问题是,在单独的模块中创建数据库模型时,在连接之间切换的正确方法是什么。

索引.js

async function db1() {
await mongoose.createConnection(
process.env.MONGODB_URI_1,
{ useMongoClient: true }
);
}

async function db2() {
await mongoose.createConnection(
process.env.MONGODB_URI_2,
{ useMongoClient: true }
);
}

模型.js

//connect to db1

const Test1 = mongoose.model('Test1', new mongoose.Schema({ name: String }));

//connect to db2

const Test2 = mongoose.model('Test2', new mongoose.Schema({ name: String }));

最佳答案

您可以使用 createConnection 返回的对象来处理多个连接。

const db1Link = await mongoose.createConnection(
process.env.MONGODB_URI_1,
{ useMongoClient: true }
);

// Connect to db1
db1Link.model('Test1', new mongoose.Schema({ name: String }));

const db2Link = await mongoose.createConnection(
process.env.MONGODB_URI_2,
{ useMongoClient: true }
);

// Connect to db2
db2Link.model('Test2', new mongoose.Schema({ name: String }));

Here is what the documentation says about it

Multiple connections

So far we've seen how to connect to MongoDB using Mongoose's default connection. At times we may need multiple connections open to Mongo, each with different read/write settings, or maybe just to different databases for example. In these cases we can utilize mongoose.createConnection() which accepts all the arguments already discussed and returns a fresh connection for you.

var conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options);

This connection object is then used to create and retrieve models. Models are always scoped to a single connection.

关于javascript - Mongoose 切换多个连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46581230/

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