개요
대부분의 애플리케이션은 단일 MongoDB 연결을 사용합니다. 그러나 일부 애플리케이션은 데이터 분리, 성능 최적화 또는 아키텍처 요구 사항을 위해 다중 연결의 이점을 누릴 수 있습니다.
이 튜토리얼에서는 단일 Node.js 애플리케이션 내에서 여러 MongoDB 연결을 설정하는 방법을 학습 .
여러 MongoDB 연결에 대한 사용 사례
여러 MongoDB 연결은 데이터 분리, 향상된 성능 또는 아키텍처 유연성이 필요한 애플리케이션에 유용합니다.
여러 MongoDB 연결의 일반적인 사용 사례는 다음과 같습니다.
멀티 테넌트 애플리케이션: 각 테넌트는 데이터 격리 및 보안을 위해 자체 연결이 있는 별도의 데이터베이스 사용합니다.
마이크로서비스 아키텍처: 각 서비스가 자체 전용 데이터베이스 연결을 유지합니다.
부하 분산: 여러 데이터베이스 인스턴스에 읽기 및 쓰기 (write) 작업을 분산합니다.
데이터 처리: 분석 또는 보고 위해 여러 MongoDB 서버에서 동시에 데이터 검색
멀티 테넌트 애플리케이션
서로 다른 테넌트 또는 고객이 동일한 웹 애플리케이션 주식 하지만 별도의 격리된 데이터베이스가 필요한 멀티 테넌트 애플리케이션 생각해 보세요. 이 시나리오에서 각 테넌트는 전용 MongoDB 연결을 가질 수 있습니다. 이렇게 하면 모두 동일한 애플리케이션 내에서 작동하는 동시에 각 테넌트에 대한 데이터 분리, 보안 및 사용자 지정이 보장됩니다. 이 접근 방식은 관리 간소화하고 기존 테넌트에 영향을 주지 않고 새 테넌트가 플랫폼에 가입함에 따라 확장하다 할 수 있는 방법을 제공합니다.
애플리케이션 에서 다중 연결을 구현 방법을 탐색할 때 다음 MongoDB 개념을 고려하세요.
이러한 개념은 효율적인 데이터 관리 및 성능 최적화를 위해 여러 개의 MongoDB 연결이 필요한 시나리오에서 중요한 역할 합니다.
튜토리얼
이 튜토리얼에서는 다음 작업을 수행합니다.
환경 설정 및 필요한 종속성 설치
MongoDB에 연결
프라이머리 MongoDB 연결 설정
세컨더리 MongoDB 연결 설정
기존 스키마 사용
스키마 유연성 설정
동일한 연결 내에서 데이터베이스 전환
전제 조건
이 튜토리얼을 시작하기 전에 MongoDB Atlas cluster 있어야 합니다. 무료 MongoDB Atlas cluster 만드는 방법을 학습하려면 Atlas 시작하기 튜토리얼을 참조하세요.
참고
이 튜토리얼에서는 MongoDB Server 8.0.12 및 Node.js 버전 20.15.1을 사용합니다.
설치 종속성
이 튜토리얼에 필요한 종속성을 설치합니다.
npm install express mongoose
이 튜토리얼에서는 웹 프레임워크 에는 Express .js를 사용하고 MongoDB 객체 모델링에는 Mongoose 합니다.
참고
이 튜토리얼에서는 널리 사용되는 MongoDB 용 ODM(객체 데이터 모델링) 라이브러리 Mongoose 사용합니다. Mongoose 시작하기에 대한 자세한 내용은 Mongoose 시작하기 튜토리얼을 참조하세요.
환경 변수 설정
프로젝트 루트 디렉토리 에 .env
파일 만들어 MongoDB 연결 문자열을 저장 .
touch .env
.env
파일 에 다음 환경 변수를 추가합니다.
PRIMARY_CONN_STR=<your-primary-connection-string> SECONDARY_CONN_STR=<your-secondary-connection-string>
자리 표시자 값을 실제 MongoDB Atlas 연결 문자열로 바꿉니다. MongoDB Atlas 연결 문자열 찾는 방법을 학습하려면 클러스터에 연결 튜토리얼을 참조하세요.
dotenv
패키지 설치하여 환경 변수를 로드합니다.
npm install dotenv
이제 애플리케이션 에서 여러 MongoDB 연결을 설정하다 준비가 된 프로젝트 생겼습니다.
프로젝트 구조
이 튜토리얼을 완료하면 이 애플리케이션 의 프로젝트 디렉토리 구조는 다음과 같습니다.
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
이 튜토리얼에서 생성할 키 파일은 다음과 같은 용도 제공 .
인덱스.js: 두 연결을 모두 가져오고 사용하는 기본 애플리케이션 파일 입니다.
db. 프라이머리.js:
mongoose.connect()
을(를) 사용하여 프라이머리 MongoDB 연결을 구성합니다.db. 세컨더리.js:
mongoose.createConnection()
을(를) 사용하여 세컨더리 MongoDB 연결을 구성합니다.제품. 스키마.js: 두 연결 모두에 대해 재사용 가능한 제품 스키마 정의합니다.
.env: MongoDB 연결 문자열을 안전하게 저장합니다.
프라이머리 MongoDB 연결 설정
이 섹션에서는 Mongoose 사용하여 애플리케이션 에서 프라이머리 MongoDB 연결을 설정하다 방법을 학습 . mongoose.connect() 메서드를 사용하여 애플리케이션 에 대한 프라이머리 MongoDB database 연결을 설정할 수 있습니다. 이 메서드는 전체 애플리케이션 에 대한 단일 연결 풀 관리합니다.
프라이머리 연결 파일 만들기
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). // You can adjust it based on your configuration. mongoose.set('strictQuery', true); // Connect to 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); } }); }
제품 스키마 만들기
애플리케이션 에서 작업을 수행하기 위한 스키마를 생성합니다. 다음 코드에 표시된 대로 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 name: String }, name: String, price: Number, category: String, description: String // add required properties }, options ); }
프라이머리 연결 사용
메인 index.js
파일 에서 db.primary.js
파일 가져오고 여기에 정의된 메서드를 사용하여 프라이머리 MongoDB 연결을 설정합니다. 필요한 경우 선택적 연결 옵션 객체 전달할 수도 있습니다.
그런 다음 product.schema.js
파일 가져와서 제품 스키마 액세스 . 이를 통해 모델을 만들고 애플리케이션 에서 제품과 관련된 작업을 수행할 수 있습니다. 다음 코드를 복사하여 index.js
파일 에 붙여넣어 프라이머리 연결을 설정하다 하고 샘플 제품 데이터에 대한 작업을 수행합니다.
// Load environment variables require('dotenv').config(); const mongoose = require("mongoose"); // Async function to establish the primary MongoDB connection 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
애플리케이션 에 여러 개의 MongoDB 연결이 필요한 경우.
세컨더리 MongoDB 연결 설정
다양한 사용 사례에 맞게 세컨더리 MongoDB 연결을 구성할 수 있습니다. 이 섹션에서는 세컨더리 연결을 설정하다 하고 사용하는 방법을 학습 .
세컨더리 연결 파일 만들기
mongoose.createConnection() 메서드를 사용하여 파일 에 연결 코드를 생성합니다.db.secondary.js
메서드. 이 메서드를 사용하면 이전에 프라이머리 MongoDB 연결에 사용한 mongoose.connect()
메서드와 달리 특정 사용 사례 나 데이터 액세스 패턴 에 맞게 각각 조정된 별도의 연결 풀을 설정할 수 있습니다.
const mongoose = require("mongoose"); module.exports = (uri, options = {}) => { // Connect to MongoDB const db = mongoose.createConnection(uri, options); // By default, Mongoose skips properties not defined in the schema (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; }
세컨더리 연결 사용
메인 index.js
파일 에서 db.secondary.js
파일 가져오고, db
라는 변수를 사용하여 연결 객체 만든 다음, 여기에 정의된 메서드를 사용하여 세컨더리 MongoDB 연결을 설정합니다. 필요한 경우 선택적 연결 옵션 객체 전달할 수도 있습니다. index.js
파일 끝에 다음 코드를 추가합니다.
// Load environment variables require('dotenv').config(); // Establish the secondary MongoDB connection 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
이제 연결을 설정하다 했으므로 새 db
객체 사용하여 모델을 만들 수 있습니다. 다음 섹션에서는 특정 데이터 액세스 및 관리 요구 사항에 가장 적합한 설정 선택하는 데 도움이 되는 다양한 시나리오와 예제를 살펴봅니다.
기존 스키마 사용
두 연결이 모두 동일한 데이터 모델 에서 작동하는 경우 프라이머리 연결에 사용된 것과 동일한 product.schema.js
파일 사용합니다.
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); } });
프로젝트 에서 프라이머리 데이터베이스 연결의 기존 스키마 세컨더리 MongoDB 연결에 사용하기 위한 실용적인 코드 예시 와 사용 가능한 리소스를 보려면 기존 스키마 사용 Github 리포지토리방문하세요.
스키마 유연성 설정
여러 MongoDB 연결로 작업할 때는 특정 사용 사례에 따라 스키마 조정할 수 있는 유연성을 갖는 것이 중요합니다. 프라이머리 연결에는 데이터 무결성을 보장하기 위해 유효성 검사 포함된 엄격한 스키마 필요할 수 있지만, 세컨더리 연결이 다른 용도로 사용되는 시나리오가 있습니다. 인스턴스, 세컨더리 연결은 분석 위해 아카이브 서버 에 데이터를 저장 수 있으며, 과거 사용 사례에 따라 다양한 스키마 요구 사항이 적용됩니다. 이 섹션에서는 애플리케이션 의 뚜렷한 요구 사항을 충족할 수 있도록 세컨더리 연결에 대한 스키마 유연성을 구성하는 방법을 알아봅니다.
Mongoose 에서 스키마 유연성을 유지하려는 경우 세컨더리 연결에 대한 스키마 구성할 때 스키마 옵션에서 strict: false
속성 전달합니다. 이를 통해 스키마 를 엄격하게 준수하지 않는 데이터로 작업할 수 있습니다.
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); } });
프로젝트 의 세컨더리 MongoDB 연결에서 스키마 유연성을 설정하는 데 필요한 실제 코드 예시 와 사용 가능한 리소스를 보려면 스키마 유연성 설정 Github 리포지토리참조하세요.
동일한 연결 내에서 데이터베이스 전환
애플리케이션의 데이터베이스 설정 내에서 db.useDb() 메서드를 사용하여 서로 다른 데이터베이스 간에 전환할 수 있습니다. 이 메서드를 사용하면 동일한 연결 풀 공유 하면서 특정 데이터베이스 와 연결된 새 연결 객체 만들 수 있습니다.
이 접근 방식을 사용하면 각 데이터베이스 에 대해 고유한 데이터 컨텍스트를 유지하면서 단일 연결을 사용하여 애플리케이션 내에서 여러 데이터베이스를 관리 할 수 있습니다.
product.schema.js
파일 가져와서 제품 스키마 액세스 합니다. 이를 통해 db
객체 사용하여 모델을 만들고 애플리케이션 에서 제품과 관련된 작업을 수행할 수 있습니다.
예제: 별도의 데이터베이스로 저장
여러 매장이 독립적으로 운영되고 각 저장 제품 관리 위해 자체 데이터베이스 유지 관리하는 전자상거래 플랫폼을 생각해 보세요. 다음 예시 와 같이 db.useDb()
메서드를 사용하여 공유 연결 풀 유지하면서 서로 다른 저장 데이터베이스 간에 전환할 수 있습니다.
// Load environment variables require('dotenv').config(); // Establish the secondary MongoDB connection 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! // 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' const storeA = db.useDb('StoreA'); // Create Model const SecondaryStoreAProductModel = storeA.model("Product", secondaryProductSchema); // Wait for Store A connection to be ready storeA.once('open', async () => { console.log('Store A database connected, executing operations...'); try { // Check if products already exist in Store 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' const storeB = db.useDb('StoreB'); // Create Model const SecondaryStoreBProductModel = storeB.model("Product", secondaryProductSchema); // Wait for Store B connection to be ready storeB.once('open', async () => { console.log('Store B database connected, executing operations...'); try { // Check if products already exist in Store 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); } });
앞의 예시 Store A
및 Store B
에 대해 별도의 데이터베이스 연결을 설정하고 각 저장 에는 자체 제품 데이터가 포함되어 있습니다. 이 접근 방식은 효율적인 리소스 관리 위해 단일 공유 연결 풀 활용하면서 데이터 분리를 제공합니다.
앞의 정적 접근 방식은 사전 정의된 이름(StoreA
, StoreB
)을 사용하여 각 저장 에 대한 명시적 연결을 생성합니다.
동적 저장 관리 의 경우 저장 식별자를 매개 변수로 받아들이고 연결 객체 반환하는 함수를 만듭니다. 이 기능을 사용하면 식별자별로 저장 전환할 수 있으며 기존 연결을 재사용하여 효율성 높일 수 있습니다.
// 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' 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 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); } });
동적 접근 방식에서는 필요에 따라 연결 인스턴스가 생성되고 캐시되므로 각 저장 에 대해 별도의 연결을 수동으로 관리할 필요가 없습니다. 이 접근 방식은 애플리케이션 의 여러 스토어와 작업해야 하는 시나리오에서 유연성과 리소스 효율성 향상시킵니다.
프로젝트 에서 동일한 연결 내의 데이터베이스를 세컨더리 MongoDB 연결로 전환하는 데 필요한 실제 코드 예시 와 사용 가능한 리소스를 보려면 Github 리포지토리방문하세요.
다음 단계
이 튜토리얼에서는 Mongoose 사용하여 Node.js 애플리케이션 에서 여러 MongoDB 연결을 구현 방법을 보여줍니다. 프라이머리 및 세컨더리 연결을 설정하고, 스키마 유연성을 구현 , 단일 연결 풀 내에서 여러 데이터베이스를 관리 학습했습니다.
이러한 기술을 사용하면 여러 데이터 컨텍스트가 필요한 애플리케이션을 위해 데이터 분리, 향상된 성능 및 아키텍처 유연성을 활성화 . 이제 특정 애플리케이션 요구 사항을 충족하는 연결 전략을 구현 수 있습니다. 여러 MongoDB 연결로 계속 작업할 때는 다음 권장사항 과 추가 리소스를 고려하세요.
모범 사례
Node.js 애플리케이션 에서 여러 MongoDB 연결을 구현할 때는 다음 권장사항 따르세요.
연결 풀링: 연결 풀링 사용하여 MongoDB 연결을 효율적으로 관리 . 연결 풀링을 사용하면 연결을 재사용하고 오버헤드 줄일 수 있습니다. 자세한 학습 은 서버 매뉴얼의 연결 풀링 및 MongoDB Node.js 운전자 문서의 연결 풀로 연결 관리를 참조하세요.
오류 처리: 적절한 오류 처리, 로깅 및 복구 메커니즘을 구현하여 연결 안정성을 보장합니다.
보안: 민감한 데이터를 처리할 때 인증, 권한 부여 및 보안 통신 관행을 구현합니다. 자세한 내용은 데이터 보호를 참조하세요.
확장성: 수평 및 수직 확장 요구 사항을 모두 지원 하도록 연결 전략을 설계합니다.
테스트: 페일오버 시나리오, 높은 로드, 리소스 제약 조건 등 다양한 조건에서 다중 연결 설정 테스트합니다.
추가 리소스
Mongoose 를 시작하는 방법에 대해 자세히 학습 타사 통합 섹션의 Get Started with Mongoose 튜토리얼을 참조하세요.
MongoDB 와 함께 Mongoose 사용하는 방법에 대해 자세히 학습하려면 Mongoose 설명서를 참조하세요.
Node.js 애플리케이션 에서 여러 MongoDB 연결을 완벽하게 구현 방법에 대해 자세히 학습하려면 Github 리포지토리를 참조하세요.