使用 Node.js 和 MongoDB 实现多租户
由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!
多租户的核心概念是隐私和数据隔离,而 MongoDB 架构(数据库和集合)则可以轻松地为租户分配数据库集合。
你应该搭建一个简单的 npm 应用程序,然后mongoose运行以下命令进行安装:
npm install mongoose --save
实现处理 MongoDB 数据库连接和切换的逻辑。在这个场景中,我将使用两种不同的方法,分别使用 ` useDband` 和 ` disconnectand`在数据库之间切换reconnect(这仅适用于测试用例)。
连接和断开方法
// mongoose import
const Mongoose = require('mongoose')
// a function that takes database name and database url as import and return a mongoose connection
const connectDb = async (dbName, dbUrl) => {
if (dbName === Mongoose.connection?.db?.databaseName) return Mongoose
try {
Mongoose.connection.close()
const mongoose = await Mongoose.connect(dbUrl, { useNewUrlParser: true })
mongoose.connection.once('open', () =>
log.info(`mongodb connected to ${dbUrl}`)
)
return mongoose
} catch (error) {
log.error(error)
}
}
module.exports = { connectDb }
使用上述方法,我们只需要数据库名称和数据库 URL。我们检查数据库名称是否已打开,如果已打开,则返回 mongoose 对象;否则,关闭所有打开的连接,并使用我们传入的 URL 重新连接到数据库。
使用数据库(推荐)方法
// mongoose import
const Mongoose = require('mongoose')
// a function that takes database name and database url as import and return a mongoose connection
const connectDb = async (dbName, dbUrl) => {
if (dbName === Mongoose.connection?.db?.databaseName) return Mongoose
try {
if( Mongoose.readyState == 1 ) {
return Mongoose.useDb(dbName)
} else {
const mongoose = await Mongoose.connect(dbUrl, {
useNewUrlParser: true })
mongoose.connection.once('open', () =>
log.info(`mongodb connected to ${dbUrl}`)
)
return mongoose.useDb(dbName)
}
} catch (error) {
log.error(error)
}
}
module.exports = { connectDb }
一个非常简单的方法,useDb我们只需要一个已打开的连接,或者创建一个新连接,然后通过从已打开的 MongoDB 连接中将数据库名称传递给useDb函数来返回一个新的 MongoDB 实例。在其他情况下,您可能需要为租户使用单独的模型(模式),以下是一个示例。
// connect to mongodb
const mongoose = await Mongoose.connect(dbUrl, {
useNewUrlParser: true })
// connect to prefer database
const db = mongoose.useDb(databaseName)
// use model(schema) preferred
db.model(modelName, schema)
把租户锁好!
文章来源:https://dev.to/codesalley/multi-tenancy-with-nodejs-and-mongodb-3gn1
