Mongoose:使用一个模型处理多个数据库

我想要的是具有相同的集合(相同的模式,确切的模型,不同的数据)和1个nodejs(expressjs + mongoose)的Web应用程序的任意数据库(50)。

示例简化情况:

我有:

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

我想要达到什么样的行为:

  • GET /api/users/ http请求正在到某个域(test-domain-39.myapp.com)
  • 应用程序获取请求的域名(testing域39),不知何故mongoose理解,当我只是做User.find({isActive: true})User.find({isActive: true})它想查询数据库39

所以我只想要一个抽象 。 我将db名称传递给mongoose,并继续使用User模型(正如我们通常在单数据库连接时所做的那样)和mongoose(如果需要的话)创build连接(如果它是对特定数据库的第一个请求),使其保持活动状态连接池中的下一个请求等

什么是最简单有效的方法来完成呢?

提前致谢!

恕我直言,虽然这是可能的MongoDB,我不会build议维护一个单独的数据库为每个域,特别是如果你期望有大量的他们。 您是否考虑过多租户模式?

下面的示例代码将用户“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(); } }); }); });