Docs Home / Node.js Driver / Connect

Multiple Connections in a Single Application单个应用程序中的多个连接

Overview概述

Most applications use a single MongoDB connection. However, some applications benefit from multiple connections for data separation, performance optimization, or architectural requirements.大多数应用程序使用单个MongoDB连接。然而,一些应用程序受益于多个连接,以实现数据分离、性能优化或架构要求。

In this tutorial, you will learn how to establish multiple MongoDB connections within a single Node.js application.在本教程中,您将学习如何在单个Node.js应用程序中建立多个MongoDB连接。

Use Cases for Multiple MongoDB Connections多个MongoDB连接的用例

Multiple MongoDB connections are useful in applications that require data separation, improved performance, or architectural flexibility.多个MongoDB连接在需要数据分离、提高性能或架构灵活性的应用程序中很有用。

Common use cases for multiple MongoDB connections include the following:多个MongoDB连接的常见用例包括以下内容:

  • Multi-tenant applications: Each tenant uses a separate database with its own connection for data isolation and security:每个租户使用一个单独的数据库,该数据库具有自己的连接,用于数据隔离和安全
  • Microservices architecture微服务架构: Each service maintains its own dedicated database connection:每个服务都维护自己的专用数据库连接
  • Load distribution负载分配: Distribute read and write operations across multiple database instances在多个数据库实例之间分配读写操作
  • Data processing数据处理: Retrieve data from multiple MongoDB servers simultaneously for analytics or reporting:同时从多个MongoDB服务器检索数据以进行分析或报告

Multi-Tenant Applications多租户应用程序

Consider a multi-tenant application where different tenants or customers share the same web application but require separate, isolated databases. In this scenario, each tenant can have their own dedicated MongoDB connection. 考虑一个多租户应用程序,其中不同的租户或客户共享同一个web应用程序,但需要单独的、隔离的数据库。在这种情况下,每个租户都可以拥有自己的专用MongoDB连接。This ensures data separation, security, and customization for each tenant while all operating within the same application. This approach simplifies management and provides a way to scale as new tenants join the platform without affecting existing ones.这确保了每个租户的数据分离、安全性和定制,同时所有租户都在同一个应用程序中运行。这种方法简化了管理,并提供了一种在新租户加入平台时进行扩展的方法,而不会影响现有租户。

Consider the following MongoDB concepts as you explore how to implement multiple connections in your application:在探索如何在应用程序中实现多个连接时,请考虑以下MongoDB概念:

These concepts play a role in scenarios where multiple MongoDB connections are required for efficient data management and performance optimization.这些概念在需要多个MongoDB连接以实现高效数据管理和性能优化的场景中起着重要作用。

Tutorial教程

In this tutorial, you will perform the following actions:在本教程中,您将执行以下操作:

  • Set up your environment and install the required dependencies设置您的环境并安装所需的依赖项
  • Connect to MongoDB连接到MongoDB
  • Set up the primary MongoDB connection设置主MongoDB连接
  • Set up secondary MongoDB connections设置辅助MongoDB连接
  • Use an existing schema使用现有架构
  • Set schema flexibility设置架构灵活性
  • Switch databases within the same connection在同一连接内切换数据库

Prerequisites先决条件

Before you begin this tutorial, you must have a MongoDB Atlas cluster. To learn how to create a free MongoDB Atlas cluster, see the MongoDB Get Started tutorial.在开始本教程之前,您必须拥有一个MongoDB Atlas集群。要了解如何创建免费的MongoDB Atlas集群,请参阅MongoDB入门教程。

Note

This tutorial uses MongoDB Server 8.0.12 and Node.js version 20.15.1.本教程使用MongoDB Server 8.0.12和Node.js版本20.15.1。

1

Create a New Project创建新项目

Create a new directory for your project and initialize a new Node.js project:为您的项目创建一个新目录并初始化一个新的Node.js项目:

mkdir mongodb-multiple-connections
cd mongodb-multiple-connections
npm init -y
2

Install Dependencies安装依赖项

Install the required dependencies for this tutorial:安装本教程所需的依赖项:

npm install express mongoose

This tutorial uses Express.js for the web framework and Mongoose for MongoDB object modeling.本教程使用Expressjs作为web框架,使用Mongoose进行MongoDB对象建模。

Note

This tutorial uses Mongoose, a popular Object Data Modeling (ODM) library for MongoDB. For more information on getting started with Mongoose, see the Get Started with Mongoose tutorial.本教程使用Mongoose,一个流行的MongoDB对象数据建模(ODM)库。有关Mongoose入门的更多信息,请参阅Mongoose教程入门

3

Set Up Environment Variables设置环境变量

Create a .env file in your project root directory to store your MongoDB connection strings:在项目根目录中创建一个.env文件来存储MongoDB连接字符串:

touch .env

Add the following environment variables to your .env file:将以下环境变量添加到.env文件中:

:orphan:

PRIMARY_CONN_STR=<your-primary-connection-string>
SECONDARY_CONN_STR=<your-secondary-connection-string>

Replace the placeholder values with your actual MongoDB Atlas connection strings. To learn how to find your MongoDB Atlas connection string, see the Connect to Your Cluster tutorial.将占位符值替换为实际的MongoDB Atlas连接字符串。要了解如何查找MongoDB Atlas连接字符串,请参阅连接到集群教程。

Install the dotenv package to load your environment variables:安装dotenv包以加载环境变量:

npm install dotenv

You now have a project that is ready to set up multiple MongoDB connections in your application.现在,您已经有了一个项目,可以在您的应用程序中设置多个MongoDB连接。

Project Structure项目结构

When you complete this tutorial, your project directory for this application will have the following structure:完成本教程后,此应用程序的项目目录将具有以下结构:

mongodb-multiple-connections/
├── .env # Environment variables
├── package.json # Project dependencies
├── package-lock.json # Dependency lock file
├── node_modules/ # Installed packages
├── index.js # Main application file
├── db.primary.js # Primary connection configuration
├── db.secondary.js # Secondary connection configuration
└── product.schema.js # Product schema definition

The key files you'll create in this tutorial serve the following purposes:您将在本教程中创建的关键文件用于以下目的:

  • index.js: Your main application file that imports and uses both connections:导入并使用这两个连接的主应用程序文件
  • db.primary.js: Configures the primary MongoDB connection using mongoose.connect():使用mongoose.connect()配置主MongoDB连接
  • db.secondary.js: Configures secondary MongoDB connections using mongoose.createConnection():使用mongoose.createConnection()配置辅助MongoDB连接
  • product.schema.js: Defines the reusable product schema for both connections:为两个连接定义可重用的产品架构
  • .env: Stores your MongoDB connection strings securely:安全地存储MongoDB连接字符串

Set Up the Primary MongoDB Connection设置主MongoDB连接

In this section, learn how to set up the primary MongoDB connection in your application by using Mongoose. Use the mongoose.connect() method to establish the primary MongoDB database connection for your application. This method manages a single connection pool for the entire application.在本节中,学习如何使用Mongoose在应用程序中设置主MongoDB连接。使用mongoose.connect()方法为您的应用程序建立主MongoDB数据库连接。此方法管理整个应用程序的单个连接池。

1

Create the Primary Connection File创建主连接文件

In a new file named db.primary.js, define a connection method to use in your main application file, index.js. This method configures the MongoDB connection and handles events. Copy and paste the following code into the db.primary.js file:在名为db.primary.js的新文件中,定义一个在主应用程序文件index.js中使用的连接方法。此方法配置MongoDB连接并处理事件。将以下代码复制并粘贴到db.primary.js文件中:

require('dotenv').config();
const mongoose = require("mongoose");

module.exports = async (uri, options = {}) => {
// By default, Mongoose skips properties not defined in the schema (strictQuery). 默认情况下,Mongoose跳过模式中未定义的属性(strictQuery)。
// You can adjust it based on your configuration.您可以根据配置进行调整。
mongoose.set('strictQuery', true);

// Connect to MongoDB连接到MongoDB
try {
await mongoose.connect(uri, options);
console.info("MongoDB primary connection initiated");
} catch (err) {
console.error("MongoDB primary connection failed, " + err);
}

// Event handling事件处理
mongoose.connection.once('open', () => console.info("MongoDB primary connection opened!"));
mongoose.connection.on('connected', () => console.info("MongoDB primary connection succeeded!"));
mongoose.connection.on('error', (err) => {
console.error("MongoDB primary connection failed, " + err);
mongoose.disconnect();
});
mongoose.connection.on('disconnected', () => console.info("MongoDB primary connection disconnected!"));

// Graceful exit优雅退出
process.on('SIGINT', async () => {
try {
await mongoose.connection.close();
console.info("Mongoose primary connection disconnected through app termination!");
process.exit(0);
} catch (err) {
console.error("Error during graceful shutdown:", err);
process.exit(1);
}
});
}
2

Create the Product Schema创建产品架构

Create schemas for performing operations in your application. Write the schema in a separate file named product.schema.js and export it, as shown in the following code:创建用于在应用程序中执行操作的模式。将模式写入名为product.schema.js的单独文件中并导出,如下代码所示:

const mongoose = require("mongoose");

module.exports = (options = {}) => {
// Schema for Product产品架构
return new mongoose.Schema(
{
store: {
_id: mongoose.Types.ObjectId, // Reference-id to the store collection商店集合的引用id
name: String
},
name: String,
price: Number,
category: String,
description: String
// add required properties添加所需属性
},
options
);
}
3

Use the Primary Connection使用主连接

Import the db.primary.js file in your main index.js file and use the method defined there to establish the primary MongoDB connection. You can also pass an optional connection options object if needed.db.primary.js文件导入到主index.js文件中,并使用其中定义的方法建立主MongoDB连接。如果需要,您还可以传递可选的连接选项对象。

Then, import the product.schema.js file to access the product schema. This lets you create a model and perform operations related to products in your application. Copy and paste the following code into your index.js file to set up the primary connection and perform operations on sample product data:然后,导入product.schema.js文件以访问产品模式。这使您可以创建模型并执行与应用程序中的产品相关的操作。将以下代码复制并粘贴到index.js文件中,以设置主连接并对示例产品数据执行操作:

// Load environment variables加载环境变量
require('dotenv').config();
const mongoose = require("mongoose");

// Async function to establish the primary MongoDB connection异步函数用于建立主MongoDB连接
async function establishPrimaryConnection() {
try {
await require("./db.primary.js")(process.env.PRIMARY_CONN_STR, {
// (optional) connection options(可选)连接选项
});
} catch (error) {
console.error('Failed to establish primary connection:', error);
process.exit(1);
}
}

// Initialize connection初始化连接
establishPrimaryConnection();

// Import Product Schema导入产品架构
const productSchema = require("./product.schema.js")({
collection: "products",
// Pass configuration options if needed如果需要,传递配置选项
});

// Create Model创建模型
const ProductModel = mongoose.model("Product", productSchema);

// Sample products data样品产品数据
const sampleProducts = [
{
name: "Laptop Pro",
price: 1299.99,
category: "Electronics",
description: "High-performance laptop for professionals"
},
{
name: "Wireless Headphones",
price: 199.99,
category: "Electronics",
description: "Premium noise-cancelling headphones"
},
{
name: "Coffee Maker",
price: 89.99,
category: "Kitchen",
description: "Automatic drip coffee maker"
}
];

// Wait for connection to be ready before executing operations执行操作前等待连接就绪
mongoose.connection.once('open', async () => {
console.log('Primary database connected, executing operations...');

try {
// Check if products already exist检查产品是否已存在
const existingCount = await ProductModel.countDocuments();
console.log(`Existing products in primary DB: ${existingCount}`);

if (existingCount === 0) {
console.log('Inserting sample products into primary database...');
await ProductModel.insertMany(sampleProducts);
console.log('Sample products inserted into primary database!');
}

// Find and display a product查找并显示产品
let product = await ProductModel.findOne();
console.log('Product found in primary DB:', product);

// Display all products显示所有产品
const allProducts = await ProductModel.find();
console.log(`Total products in primary DB: ${allProducts.length}`);
} catch (error) {
console.error('Error with primary database operations:', error);
}
});
Primary database connected, executing operations...
MongoDB primary connection initiated
Existing products in primary DB: 3
Product found in primary DB: {
_id: new ObjectId('...'),
name: 'Laptop Pro',
__v: 0
}
Total products in primary DB: 3

where your application requires multiple MongoDB connections.您的应用程序需要多个MongoDB连接。

Set Up Secondary MongoDB Connections设置辅助MongoDB连接

You can configure secondary MongoDB connections for various use cases. In this section, learn how to set up and use the secondary connection.您可以为各种用例配置辅助MongoDB连接。在本节中,学习如何设置和使用辅助连接。

1

Create the Secondary Connection File创建辅助连接文件

Create a connection code in a db.secondary.js file by using the mongoose.createConnection() method. 使用mongoose.createConnection()方法在db.secondary.js文件中创建连接代码。This method allows you to establish separate connection pools each tailored to a specific use case or data access pattern, unlike the mongoose.connect() method that you used previously for the primary MongoDB connection:此方法允许您建立单独的连接池,每个连接池都根据特定的用例或数据访问模式进行定制,这与您之前用于主MongoDB连接的mongoose.connect()方法不同:

const mongoose = require("mongoose");

module.exports = (uri, options = {}) => {
// Connect to MongoDB连接到MongoDB
const db = mongoose.createConnection(uri, options);

// By default, Mongoose skips properties not defined in the schema (strictQuery). 默认情况下,Mongoose跳过模式中未定义的属性(strictQuery)。
// Adjust it based on your configuration.根据您的配置进行调整。
db.set('strictQuery', true);

// Event handling事件处理
db.once('open', () => console.info("MongoDB secondary connection opened!"));
db.on('connected', () => console.info(`MongoDB secondary connection succeeded!`));
db.on('error', (err) => {
console.error(`MongoDB secondary connection failed, ` + err);
db.close();
});
db.on('disconnected', () => console.info(`MongoDB secondary connection disconnected!`));

// Graceful exit
process.on('SIGINT', async () => {
try {
await db.close();
console.info(`Mongoose secondary connection disconnected through app termination!`);
process.exit(0);
} catch (err) {
console.error("Error during graceful shutdown:", err);
process.exit(1);
}
});

// Export db object导出数据库对象
return db;
}
2

Use the Secondary Connection使用辅助连接

Import the db.secondary.js file in your main index.js file, create the connection object with a variable named db, and use the method defined there to establish the secondary MongoDB connection. 在主index.js文件中导入db.secondary.js文件,使用名为db的变量创建连接对象,并使用其中定义的方法建立辅助MongoDB连接。You can also pass an optional connection options object if needed. Add the following code to the end of the index.js file:如果需要,您还可以传递可选的连接选项对象。将以下代码添加到index.js文件的末尾:

// Load environment variables加载环境变量
require('dotenv').config();

// Establish the secondary MongoDB connection建立二级MongoDB连接
const db = require("./db.secondary.js")(process.env.SECONDARY_CONN_STR, {
// (optional) connection options(可选)连接选项
});

// Import Product Schema导入产品架构
const SecondaryProductSchema = require("./product.schema.js")({
collection: "products",
// Pass configuration options if needed如果需要,传递配置选项
});

// Create Model using the secondary connection使用辅助连接创建模型
const SecondaryProductModel = db.model("Product", SecondaryProductSchema);

// Sample products data for secondary database辅助数据库的示例产品数据
const SecondarySampleProducts = [
{
name: "Smart Watch",
price: 199.99,
category: "Electronics",
description: "Advanced fitness tracking smartwatch"
},
{
name: "Bluetooth Speaker",
price: 79.99,
category: "Electronics",
description: "Portable wireless speaker with premium sound"
},
{
name: "Desk Lamp",
price: 49.99,
category: "Home",
description: "LED desk lamp with adjustable brightness"
}
];

// Wait for secondary connection to be ready before executing operations在执行操作之前,等待辅助连接就绪
db.once('open', async () => {
console.log('Secondary database connected, executing operations...');

try {
// Check if products already exist检查产品是否已存在
const existingCount = await SecondaryProductModel.countDocuments();
console.log(`Existing products in secondary DB: ${existingCount}`);

if (existingCount === 0) {
console.log('Inserting sample products into secondary database...');
await SecondaryProductModel.insertMany(SecondarySampleProducts);
console.log('Sample products inserted into secondary database!');
}

// Find and display a product查找并显示产品
let product = await SecondaryProductModel.findOne();
console.log('Product found in secondary DB:', product);

// Display all products显示所有产品
const allProducts = await SecondaryProductModel.find();
console.log(`Total products in secondary DB: ${allProducts.length}`);
} catch (error) {
console.error('Error with secondary database operations:', error);
}
});
Primary database connected, executing operations...
MongoDB primary connection initiated
MongoDB secondary connection succeeded!
MongoDB secondary connection opened!
Secondary database connected, executing operations...
Existing products in primary DB: 3
Existing products in secondary DB: 6
Product found in primary DB: {
_id: new ObjectId('...'),
name: 'Laptop Pro',
__v: 0
}
Product found in secondary DB: {
_id: new ObjectId('...'),
name: 'Smart Watch',
__v: 0
}
Total products in primary DB: 3
Total products in secondary DB: 3

Now that you've set up the connection, you can use the new db object to create a model. The following sections explore different scenarios and examples to help you choose the setup that best aligns with your specific data access and management needs.现在您已经设置了连接,可以使用新的db对象创建模型。以下部分探讨了不同的场景和示例,以帮助您选择最符合您特定数据访问和管理需求的设置。

Use an Existing Schema使用现有架构

If both connections operate on the same data model, use the same product.schema.js file that was employed in the primary connection.如果两个连接都在相同的数据模型上运行,请使用主连接中使用的相同product.schema.js文件。

Import the product.schema.js file to access the product schema. This enables you to create a model by using the db object and perform operations related to products in your application:导入product.schema.js文件以访问产品架构。这使您能够使用db对象创建模型,并执行与应用程序中的产品相关的操作:

// Import Product Schema导入产品架构
const secondaryProductSchema = require("./product.schema.js")({
collection: "products",
// Pass configuration options if needed如果需要,传递配置选项
});

// Create Model创建模型
const SecondaryProductModel = db.model("Product", secondaryProductSchema);

// Wait for secondary connection to be ready before executing operations在执行操作之前,等待辅助连接就绪
db.once('open', async () => {
console.log('Secondary database connected, executing operations...');

try {
// Check if products already exist in secondary database检查辅助数据库中是否已存在产品
const existingCount = await SecondaryProductModel.countDocuments();
console.log(`Existing products in secondary DB: ${existingCount}`);

if (existingCount === 0) {
console.log('Inserting sample products into secondary database...');
await SecondaryProductModel.insertMany(sampleProducts);
console.log('Sample products inserted into secondary database!');
}

// Find and display a product查找并显示产品
let product = await SecondaryProductModel.findOne();
console.log('Product found in secondary DB:', product);

// Display all products显示所有产品
const allProducts = await SecondaryProductModel.find();
console.log(`Total products in secondary DB: ${allProducts.length}`);
} catch (error) {
console.error('Error with secondary database operations:', error);
}
});

To see a practical code example and available resources for using the existing schema of a primary database connection into a secondary MongoDB connection in your project, visit the Using the Existing Schema GitHub repository.要查看在项目中将主数据库连接的现有模式用于辅助MongoDB连接的实际代码示例和可用资源,请访问使用现有模式GitHub存储库

Set Schema Flexibility设置架构灵活性

When working with multiple MongoDB connections, it's essential to have the flexibility to adapt your schema based on specific use cases. Although the primary connection might demand a strict schema with validation to ensure data integrity, there are scenarios where a secondary connection serves a different purpose. 当处理多个MongoDB连接时,必须具有根据特定用例调整模式的灵活性。虽然主连接可能需要一个严格的模式和验证来确保数据完整性,但在某些情况下,辅助连接有不同的用途。For instance, a secondary connection might store data for analytics on an archive server, with varying schema requirements driven by past use cases. In this section, you'll explore how to configure schema flexibility for your secondary connection, allowing you to meet the distinct needs of your application.例如,辅助连接可能会在归档服务器上存储数据以供分析,而过去的用例会驱动不同的模式要求。在本节中,您将探索如何为辅助连接配置模式灵活性,以满足应用程序的不同需求。

If you prefer to have schema flexibility in Mongoose, pass the strict: false property in the schema options when configuring your schema for the secondary connection. This allows you to work with data that doesn't adhere strictly to the schema.如果您希望在Mongoose中具有模式灵活性,请在为辅助连接配置模式时在模式选项中传递strict: false属性。这允许您处理不严格遵守模式的数据。

Import the product.schema.js file to access the product schema. This enables you to create a model by using the db object and perform operations related to products in your application:导入product.schema.js文件以访问产品架构。这使您能够使用db对象创建模型,并执行与应用程序中的产品相关的操作:

// Import Product Schema导入产品架构
const secondaryProductSchema = require("./product.schema.js")({
collection: "products",
strict: false
// Pass configuration options if needed如果需要,传递配置选项
});

// Create Model创建模型
const SecondaryProductModel = db.model("Product", secondaryProductSchema);

// Wait for secondary connection to be ready before executing operations在执行操作之前,等待辅助连接就绪
db.once('open', async () => {
console.log('Secondary database (flexible schema) connected, executing operations...');

try {
// Check if products already exist in secondary database检查辅助数据库中是否已存在产品
const existingCount = await SecondaryProductModel.countDocuments();
console.log(`Existing products in secondary DB: ${existingCount}`);

if (existingCount === 0) {
// Add extra fields to demonstrate schema flexibility添加额外字段以展示模式灵活性
const flexibleSampleProducts = sampleProducts.map(product => ({
...product,
extraField: "This field is not in the schema but will be saved due to strict: false",
timestamp: new Date()
}));

console.log('Inserting sample products with extra fields into secondary database...');
await SecondaryProductModel.insertMany(flexibleSampleProducts);
console.log('Sample products with extra fields inserted into secondary database!');
}

// Find and display a product查找并显示产品
let product = await SecondaryProductModel.findOne();
console.log('Product found in secondary DB (flexible schema):', product);

// Display all products显示所有产品
const allProducts = await SecondaryProductModel.find();
console.log(`Total products in secondary DB: ${allProducts.length}`);
} catch (error) {
console.error('Error with secondary database operations:', error);
}
});

To view a practical code example and available resources for setting schema flexibility in a secondary MongoDB connection in your project, see the Setting Schema Flexibility GitHub repository.要查看在项目中的辅助MongoDB连接中设置模式灵活性的实际代码示例和可用资源,请参阅设置模式灵活性GitHub存储库

Switch Databases Within the Same Connection在同一连接内切换数据库

Within your application's database setup, you can switch between different databases by using the db.useDb() method. This method lets you to create a new connection object associated with a specific database while sharing the same connection pool.在应用程序的数据库设置中,您可以使用db.useDb()方法在不同的数据库之间切换。此方法允许您在共享同一连接池的同时创建与特定数据库关联的新连接对象。

This approach allows you to manage multiple databases within your application, by using a single connection while maintaining distinct data contexts for each database.这种方法允许您通过使用单个连接来管理应用程序中的多个数据库,同时为每个数据库维护不同的数据上下文。

Import the product.schema.js file to access the product schema. This lets you to create a model by using the db object and perform operations related to products in your application.导入product.schema.js文件以访问产品架构。这使您可以使用db对象创建模型,并执行与应用程序中的产品相关的操作。

Example: Store with Separate Database示例:使用单独的数据库存储

Consider an e-commerce platform where multiple stores operate independently, with each store maintaining its own database for product management. Use the db.useDb() method to switch between different store databases while maintaining a shared connection pool, as shown in the following example:考虑一个电子商务平台,其中多家商店独立运营,每家商店都维护自己的数据库进行产品管理。使用db.useDb()方法在维护共享连接池的同时在不同的存储数据库之间切换,如下例所示:

// Load environment variables加载环境变量
require('dotenv').config();

// Establish the secondary MongoDB connection建立二级MongoDB连接
const db = require("./db.secondary.js")(process.env.SECONDARY_CONN_STR, {
// (optional) connection options
});

// Import Product Schema导入产品架构
const secondaryProductSchema = require("./product.schema.js")({
collection: "products",
// strict: false // that doesn't adhere strictly to the schema!strict:false//不严格遵守模式!
// Pass configuration options if needed如果需要,传递配置选项
});

// Base sample products data基础样品产品数据
const sampleProducts = [
{
name: "Laptop Pro",
price: 1299.99,
category: "Electronics",
description: "High-performance laptop for professionals"
},
{
name: "Wireless Headphones",
price: 199.99,
category: "Electronics",
description: "Premium noise-cancelling headphones"
},
{
name: "Coffee Maker",
price: 89.99,
category: "Kitchen",
description: "Automatic drip coffee maker"
}
];

// Sample store-specific products样品店特定产品
const storeAProducts = sampleProducts.map(product => ({
...product,
store: { name: "Store A" },
storeId: "A"
}));

const storeBProducts = [
{
name: "Gaming Chair",
price: 299.99,
category: "Furniture",
description: "Ergonomic gaming chair with RGB lighting",
store: { name: "Store B" },
storeId: "B"
},
{
name: "Mechanical Keyboard",
price: 149.99,
category: "Electronics",
description: "RGB mechanical gaming keyboard",
store: { name: "Store B" },
storeId: "B"
}
];

// Create a connection for 'Store A'为“商店a”创建连接
const storeA = db.useDb('StoreA');

// Create Model创建模型
const SecondaryStoreAProductModel = storeA.model("Product", secondaryProductSchema);

// Wait for Store A connection to be ready等待存储A连接就绪
storeA.once('open', async () => {
console.log('Store A database connected, executing operations...');

try {
// Check if products already exist in Store A检查商店A中是否已存在产品
const existingCount = await SecondaryStoreAProductModel.countDocuments();
console.log(`Existing products in Store A: ${existingCount}`);

if (existingCount === 0) {
console.log('Inserting sample products into Store A database...');
await SecondaryStoreAProductModel.insertMany(storeAProducts);
console.log('Sample products inserted into Store A database!');
}

// Find and display a product查找并显示产品
let product = await SecondaryStoreAProductModel.findOne();
console.log('Product found in Store A:', product);

// Display all products显示所有产品
const allProducts = await SecondaryStoreAProductModel.find();
console.log(`Total products in Store A: ${allProducts.length}`);
} catch (error) {
console.error('Error with Store A operations:', error);
}
});

// Create a connection for 'Store B'为“Store B”创建连接
const storeB = db.useDb('StoreB');

// Create Model
const SecondaryStoreBProductModel = storeB.model("Product", secondaryProductSchema);

// Wait for Store B connection to be ready等待存储B连接就绪
storeB.once('open', async () => {
console.log('Store B database connected, executing operations...');

try {
// Check if products already exist in Store B检查商店B中是否已存在产品
const existingCount = await SecondaryStoreBProductModel.countDocuments();
console.log(`Existing products in Store B: ${existingCount}`);

if (existingCount === 0) {
console.log('Inserting sample products into Store B database...');
await SecondaryStoreBProductModel.insertMany(storeBProducts);
console.log('Sample products inserted into Store B database!');
}

// Find and display a product查找并显示产品
let product = await SecondaryStoreBProductModel.findOne();
console.log('Product found in Store B:', product);

// Display all products显示所有产品
const allProducts = await SecondaryStoreBProductModel.find();
console.log(`Total products in Store B: ${allProducts.length}`);
} catch (error) {
console.error('Error with Store B operations:', error);
}
});

The preceding example establishes separate database connections for Store A and Store B, with each store containing its own product data. This approach provides data separation while utilizing a single shared connection pool for efficient resource management.前面的示例为Store AStore B建立了单独的数据库连接,每个商店都包含自己的产品数据。这种方法在利用单个共享连接池进行高效资源管理的同时提供了数据分离。

The preceding static approach creates explicit connections for each store with predefined names (StoreA, StoreB).前面的静态方法为每个具有预定义名称(StoreAStoreB)的存储创建显式连接。

For dynamic store management, create a function that accepts a store identifier as a parameter and returns a connection object. This function enables store switching by identifier and reuses existing connections for improved efficiency.对于动态存储管理,创建一个函数,该函数接受存储标识符作为参数并返回连接对象。此功能允许通过标识符进行存储切换,并重用现有连接以提高效率。

// Function to get connection object for particular store's database获取特定商店数据库连接对象的函数
function getStoreConnection(storeId) {
return db.useDb("Store"+storeId, { useCache: true });
}

// Create a connection for 'Store A'为“商店a”创建连接
const store = getStoreConnection("A");

// Create Model创建模型
const SecondaryStoreProductModel = store.model("Product", secondaryProductSchema);

// Wait for store connection to be ready等待商店连接就绪
store.once('open', async () => {
console.log('Store A (dynamic) database connected, executing operations...');

try {
// Check if products already exist in the store检查商店中是否已有产品
const existingCount = await SecondaryStoreProductModel.countDocuments();
console.log(`Existing products in Store A (dynamic): ${existingCount}`);

if (existingCount === 0) {
// Use the same store A products from the previous example使用上一示例中的同一商店A产品
console.log('Inserting sample products into Store A (dynamic) database...');
await SecondaryStoreProductModel.insertMany(storeAProducts);
console.log('Sample products inserted into Store A (dynamic) database!');
}

// Find and display a product查找并显示产品
let product = await SecondaryStoreProductModel.findOne();
console.log('Product found in Store A (dynamic):', product);

// Display all products显示所有产品
const allProducts = await SecondaryStoreProductModel.find();
console.log(`Total products in Store A (dynamic): ${allProducts.length}`);
} catch (error) {
console.error('Error with Store A (dynamic) operations:', error);
}
});

In the dynamic approach, connection instances are created and cached as needed, eliminating the need for manually managing separate connections for each store. This approach enhances flexibility and resource efficiency in scenarios where you need to work with multiple stores in your application.在动态方法中,根据需要创建和缓存连接实例,从而消除了手动管理每个存储的单独连接的需要。在需要在应用程序中使用多个存储的情况下,这种方法提高了灵活性和资源效率。

To see a practical code example and available resources for switching databases within the same connection into a secondary MongoDB connection in your project, visit the GitHub repository.要查看将同一连接中的数据库切换到项目中的辅助MongoDB连接的实际代码示例和可用资源,请访问GitHub存储库

Next Steps后续步骤

This tutorial demonstrates how to implement multiple MongoDB connections in a Node.js application by using Mongoose. You learned to establish primary and secondary connections, implement schema flexibility, and manage multiple databases within a single connection pool.本教程演示了如何使用Mongoose在Node.js应用程序中实现多个MongoDB连接。您学习了如何建立主连接和辅助连接,实现模式灵活性,以及在单个连接池中管理多个数据库。

These techniques enable data separation, improved performance, and architectural flexibility for applications requiring multiple data contexts. You can now implement connection strategies that meet your specific application requirements. Consider the following best practices and additional resources as you continue to work with multiple MongoDB connections.这些技术实现了数据分离,提高了性能,并为需要多个数据上下文的应用程序提供了架构灵活性。现在,您可以实现满足特定应用程序要求的连接策略。在继续使用多个MongoDB连接时,请考虑以下最佳实践和其他资源。

Best Practices最佳实践

When implementing multiple MongoDB connections in your Node.js application, follow these best practices:在Node.js应用程序中实现多个MongoDB连接时,请遵循以下最佳实践:

  • Connection pooling连接池: Use connection pooling to manage MongoDB connections efficiently. Connection pooling enables connection reuse and reduces overhead. :使用连接池高效管理MongoDB连接。连接池支持连接重用并减少开销。To learn more, see Connection Pooling in the Server manual and Manage Connections with Connection Pools in the MongoDB Node.js driver documentation.要了解更多信息,请参阅服务器手册中的连接池和MongoDB Node.js驱动程序文档中的使用连接池管理连接
  • Error handling错误处理: Implement proper error handling, logging, and recovery mechanisms to ensure connection reliability.:实施适当的错误处理、日志记录和恢复机制,以确保连接可靠性。
  • Security安全: Implement authentication, authorization, and secure communication practices when handling sensitive data. For more information, see Secure Your Data.:在处理敏感数据时实施身份验证、授权和安全通信实践。有关更多信息,请参阅保护您的数据
  • Scalability可扩展性: Design your connection strategy to support both horizontal and vertical scaling requirements.:设计您的连接策略,以支持水平和垂直扩展要求。
  • Testing测试: Test your multiple connection setup under various conditions, including failover scenarios, high load, and resource constraints.:在各种条件下测试您的多连接设置,包括故障转移场景、高负载和资源限制。

Additional Resources其他资源

To learn more about getting started with Mongoose, see the Get Started with Mongoose tutorial in the Third-Party Integrations section.要了解有关开始使用Mongoose的更多信息,请参阅第三方集成部分中的Mongoose入门教程

To learn more about using Mongoose with MongoDB, see the Mongoose documentation.要了解有关在MongoDB中使用Mongoose的更多信息,请参阅Mongoose文档

To learn more about the complete implementation of multiple MongoDB connections in a Node.js application, see the GitHub repository.要了解更多关于Node.js应用程序中多个MongoDB连接的完整实现,请参阅GitHub存储库