【发布时间】:2019-11-29 14:48:18
【问题描述】:
我想了解如何在 mongoose 全局承诺连接中在数据库之间切换。
我当前的连接是这样建立的app.ts
import * as mongoose from 'mongoose';
...
try {
await mongoose.createConnection(`mongodb://localhost:27017/db1`, {
useNewUrlParser: true,
})
console.log("Connected")
} catch (error) {
console.log(error)
}
然后我在不同的文件中访问它some.model.ts
import { Schema, Document, model } from 'mongoose';
const SomeSchema: Schema = new Schema({
name: { type: String, required: true },
owner: { type: string, required: true }
});
export default model('Some', SomeSchema);
根据文档。
到目前为止,我们已经了解了如何使用 Mongoose 的默认连接连接到 MongoDB。有时我们可能需要打开多个连接到 Mongo,每个连接都有不同的读/写设置,或者可能只是连接到不同的数据库。在这些情况下,我们可以利用 mongoose.createConnection() 接受所有已经讨论过的参数并为您返回一个新的连接。
const conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options);
我可以像这样创建多个数据库连接
try {
const db1 = await mongoose.createConnection(`mongodb://localhost:27017/db1`, {
useNewUrlParser: true,
})
const db2 = await mongoose.createConnection(`mongodb://localhost:27017/db2`, {
useNewUrlParser: true,
})
console.log("Connected")
} catch (error) {
console.log(error)
}
我可以在console.log(mongoose.connections)看到这两个连接
但是如何在some.model.ts 中指定模型应该使用哪个数据库?
import { Schema, Document, model } from 'mongoose';
const SomeSchema: Schema = new Schema({
name: { type: String, required: true },
owner: { type: string, required: true }
});
export default SPECIFY_DATABASE.model('Some', SomeSchema);
我发现了其他问题,例如this,但是创建了“本地”连接,我需要在许多不同的文件中使用猫鼬连接。
感谢您的回答,如果您需要更多解释,请现在告诉我。
【问题讨论】:
标签: node.js mongodb typescript mongoose