如何使用Mongoose在Mongo数据库之间切换?

huangapple go评论100阅读模式
英文:

How to switch between Mongo databases using Mongoose?

问题

What I want to do is to use different databases for different users, for example I have 3 users that would connect to:

www.user1.myfrontend.com

www.user2.myfrontend.com

www.user3.myfrontend.com

Let's suppose that each user wants to display the list of products he has, a GET request would be sent to the backend and from there I will connect to the database of the user:

mongodb://mongodatabse:secret@server/databaseOfUser1
mongodb://mongodatabse:secret@server/databaseOfUser2
mongodb://mongodatabse:secret@server/databaseOfUser3

What I did so far:

I connect to the database called config at the start of the app:

db.js

  1. const connect = (uri, app, database="config") => {
  2. const db = mongoose
  3. .createConnection(uri, { useNewUrlParser: true, useUnifiedTopology: true })
  4. db.on('open', () => {
  5. mongoose.connection.useDb("config")
  6. app.emit('dbReady');
  7. return true;
  8. });
  9. db.on('error', (err) => {
  10. console.log(`Couldn't connect to database: ${err.message}`);
  11. return false;
  12. });
  13. };

server.js

  1. db.connect(process.env.MONGODB_URL, app);
  2. app.on('dbReady', function () {
  3. server.listen(PORT, () => {
  4. console.info(`> Frontend is hosted @: ${process.env.BASE_URL}`);
  5. console.info(`> Database is hosted @: ${process.env.mongodb_url}`);
  6. console.info(`> Listening on port ${PORT}`);
  7. });
  8. });

Then whenever I receive a request I check in the config database for the database to use:

app.js:

  1. const AccessConfig = require('./models/schemas/AccessConfigSchema');
  2. const db = require('./models/db');
  3. app.use(async (req, res, next) => {
  4. const subdomain = req.subdomains[req.subdomains.length - 1];
  5. try {
  6. let database = await AccessConfig.findOne({ subdomain: subdomain });
  7. if (!database)
  8. database = await AccessConfig.findOne({ subdomain: "demo" });
  9. console.log(database);
  10. db.useDb(database);
  11. next();
  12. } catch (e) {
  13. console.log(e.message)
  14. return res.status(500).send('Error: ' + e.message);
  15. }
  16. });

So far, it seems like the database isn't changing, and I'm not even sure if this is the correct implementation or if there are too many connections open, etc.

英文:

What I want to do is to use different databases for different users, for example I have 3 users that would connect to:

www.user1.myfrontend.com

www.user2.myfrontend.com

www.user3.myfrontend.com

Let's suppose that each user want to display the list of products he has, a GET request would be sent to the backend and from there I will connect to the database of the user:

mongodb://mongodatabse:secret@server/databaseOfUser1
mongodb://mongodatabse:secret@server/databaseOfUser2
mongodb://mongodatabse:secret@server/databaseOfUser3

What I did so far:

I connect to the database called config at the start of the app:

db.js

  1. const connect = (uri, app, database="config") => {
  2. const db= mongoose
  3. .createConnection(uri,{ useNewUrlParser: true, useUnifiedTopology: true })
  4. db.on('open', () => {
  5. mongoose.connection.useDb("config")
  6. app.emit('dbReady');
  7. return true;
  8. });
  9. db.on('error', (err) => {
  10. console.log(`Couldn't connect to database': ${err.message}`);
  11. return false;
  12. });
  13. };

server.js

  1. db.connect(process.env.MONGODB_URL, app);
  2. app.on('dbReady', function () {
  3. server.listen(PORT, () => {
  4. console.info(`> Frontend is hosted @: ${process.env.BASE_URL}`);
  5. console.info(`> Database is hosted @: ${process.env.mongodb_url}`);
  6. console.info(`> Listening on port ${PORT}`);
  7. });
  8. });

Then whenever I receive a request I check in the config database for the database to use:

app.js:

  1. const AccessConfig = require('./models/schemas/AccessConfigSchema');
  2. const db = require('./models/db');
  3. app.use(async (req, res, next) => {
  4. const subdomain = req.subdomains[req.subdomains.length - 1];
  5. try {
  6. let database = await AccessConfig.findOne({ subdomain: subdomain});
  7. if (!database)
  8. database= await AccessConfig.findOne({ subdomain: "demo"});
  9. console.log(database);
  10. db.useDb(database);
  11. next();
  12. } catch (e) {
  13. console.log(e.message)
  14. return res.status(500).send('Error: ' + e.message);
  15. }
  16. });

So far It seems like the database isn't changing and I'm not even sure that this is the correct implementation or too many connections are open, etc.

答案1

得分: 1

我明白了,您可以使用以下代码创建连接

  1. //DB_URI_USER1=mongodb://mongodatabse:secret@server/databaseOfUser1
  2. //DB_URI_USER2=mongodb://mongodatabse:secret@server/databaseOfUser2
  3. const user1Connection = mongoose.createConnection(process.env.DB_URI_USER1, {
  4. useNewUrlParser: true,
  5. useUnifiedTopology: true,
  6. })
  7. const user2Connection = mongoose.createConnection(process.env.DB_URI_USER2, {
  8. useNewUrlParser: true,
  9. useUnifiedTopology: true,
  10. })

然后为每个创建模型:

  1. const User1 = user1Connection.model(...)
  2. const User2 = user2Connection.model(...)

现在在API中查询所需的模型。

对我有用 如何使用Mongoose在Mongo数据库之间切换?

英文:

I figured out, you can create connections using

  1. //DB_URI_USER1=mongodb://mongodatabse:secret@server/databaseOfUser1
  2. //DB_URI_USER2=mongodb://mongodatabse:secret@server/databaseOfUser2
  3. const user1Connection = mongoose.createConnection(process.env.DB_URI_USER1, {
  4. useNewUrlParser: true,
  5. useUnifiedTopology: true,
  6. })
  7. const user2Connection = mongoose.createConnection(process.env.DB_URI_USER2, {
  8. useNewUrlParser: true,
  9. useUnifiedTopology: true,
  10. })

Then you create the model for each

  1. const User1 = user1Connection.model(...)
  2. const User2 = user2Connection.model(...)

Now on the API you query the desired model.

Working for me 如何使用Mongoose在Mongo数据库之间切换?

huangapple
  • 本文由 发表于 2023年1月4日 15:34:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75002203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定