【问题标题】:Mongoose: handling multiple databases when working with one modelMongoose:使用一个模型时处理多个数据库
【发布时间】:2017-08-15 08:46:39
【问题描述】:

我想要的是拥有具有相同集合(相同模式、精确模型、不同数据)和 1 个 nodejs(expressjs + mongoose)网络应用程序的任意数据库(例如 50 个)。

示例简化案例:

我有:

  • 带有User 模型的单个 Web 应用程序(expressjs + mongoose)。
  • 50 个域 50 个数据库,包含 users 集合。

我想要实现什么行为:

  • GET /api/users/ http 请求即将到达域之一 (test-domain-39.myapp.com)
  • app 获取了请求的域名 (test-domain-39),当我在 users.controller 中执行 User.find({isActive: true}) 时,猫鼬不知何故明白它想要查询 database-39

所以我只想要一个抽象。我将数据库名称传递给 mongoose 并继续使用User 模型(就像我们通常在拥有单个数据库连接时所做的那样),如果需要,mongoose 创建连接(如果它是对特定数据库的第一个请求),保留它连接池中的下一个请求等。

实现这一目标的最简单、最有效的方法是什么?

提前致谢!

【问题讨论】:

    标签: node.js express design-patterns mongoose high-load


    【解决方案1】:

    恕我直言,虽然 MongoDB 可以做到这一点,但我不建议为每个域维护一个单独的数据库,尤其是在您期望拥有大量此类数据库的情况下。您是否考虑过使用多租户模型?

    下面的示例代码将用户“Alex”添加到两个不同的数据库中,“domainOne”和“domainTwo”。希望这会有所帮助

    var mongoose = require('mongoose');
    var personSchema = { name: String, domain : String };
    var baseUri = 'mongodb://localhost/';
    
    domains.forEach((domain) => {
        var conn = mongoose.createConnection(baseUri + domain, (error) => {
        if(error){
            console.log('Ups! Database connection failed!');
            return;
        }
        //Use the connection object to create your models,
        //instead the mongoose object
        //so that our data is saved into the database
        //associated with this connection
        var Person = conn.model('Person', personSchema);
    
        //Lets add user 'Alex' into the database
        (new Person({name : 'Alex', domain : domain })).save((error) => {
            if(error){
                console.log('Ups! Could not save person');
            } else {
                conn.close();
            }
        });
        });
    });
    

    【讨论】:

    • 很高兴为您提供帮助!如果这回答了你的问题,请告诉我@7sides
    猜你喜欢
    • 2016-07-02
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2020-07-06
    • 2014-09-17
    • 2016-12-21
    相关资源
    最近更新 更多