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

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

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

const connect = (uri, app, database="config") => {
   const db = mongoose
        .createConnection(uri, { useNewUrlParser: true, useUnifiedTopology: true })
    db.on('open', () => {
        mongoose.connection.useDb("config")
        app.emit('dbReady');
        return true;
    });

    db.on('error', (err) => {
        console.log(`Couldn't connect to database: ${err.message}`);
        return false;
    });
};

server.js

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

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

app.js:

const AccessConfig = require('./models/schemas/AccessConfigSchema');
const db = require('./models/db');
app.use(async (req, res, next) => {
    const subdomain = req.subdomains[req.subdomains.length - 1];
    try {
        let database = await AccessConfig.findOne({ subdomain: subdomain });
        if (!database)
            database = await AccessConfig.findOne({ subdomain: "demo" });
        console.log(database);
        db.useDb(database);
        next();
    } catch (e) {
        console.log(e.message)
        return res.status(500).send('Error: ' + e.message);
    }
});

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

const connect = (uri, app, database="config") => {
   const db= mongoose
        .createConnection(uri,{ useNewUrlParser: true, useUnifiedTopology: true })
    db.on('open', () => {
        mongoose.connection.useDb("config")
        app.emit('dbReady');
        return true;
    });

    db.on('error', (err) => {
        console.log(`Couldn't connect to database': ${err.message}`);
        return false;
    });
};

server.js

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

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

app.js:

const AccessConfig = require('./models/schemas/AccessConfigSchema');
const db = require('./models/db');
app.use(async (req, res, next) => {
    const subdomain = req.subdomains[req.subdomains.length - 1];
    try {
        let database = await AccessConfig.findOne({ subdomain: subdomain});
        if (!database)
            database= await AccessConfig.findOne({ subdomain: "demo"});
        console.log(database);
        db.useDb(database);
        next();
    } catch (e) {
        console.log(e.message)
        return res.status(500).send('Error: ' + e.message);
    }

});

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

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

//DB_URI_USER1=mongodb://mongodatabse:secret@server/databaseOfUser1 

//DB_URI_USER2=mongodb://mongodatabse:secret@server/databaseOfUser2

const user1Connection = mongoose.createConnection(process.env.DB_URI_USER1, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})

const user2Connection = mongoose.createConnection(process.env.DB_URI_USER2, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})

然后为每个创建模型:

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

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

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

英文:

I figured out, you can create connections using

//DB_URI_USER1=mongodb://mongodatabse:secret@server/databaseOfUser1 

//DB_URI_USER2=mongodb://mongodatabse:secret@server/databaseOfUser2

   const user1Connection = mongoose.createConnection(process.env.DB_URI_USER1, {
   	useNewUrlParser: true,
   	useUnifiedTopology: true,
   })

   const user2Connection = mongoose.createConnection(process.env.DB_URI_USER2, {
   	useNewUrlParser: true,
   	useUnifiedTopology: true,
   })

Then you create the model for each

const User1 = user1Connection.model(...)
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:

确定