Skip to content

数据库集成核心功能实现

这是一个最小但完整的数据库集成实现,展示了 MongoDB 和 PostgreSQL 的核心概念和实现方式。

项目结构

database-integration/
├── src/
│   ├── mongodb/
│   │   ├── connection.js      # MongoDB 连接
│   │   ├── models/
│   │   │   ├── user.js       # 用户模型
│   │   │   ├── article.js    # 文章模型
│   │   │   └── comment.js    # 评论模型
│   │   └── repositories/
│   │       ├── user-repo.js   # 用户仓库
│   │       ├── article-repo.js # 文章仓库
│   │       └── comment-repo.js # 评论仓库
│   ├── postgresql/
│   │   ├── connection.js      # PostgreSQL 连接
│   │   ├── models/
│   │   │   ├── user.js       # 用户模型
│   │   │   ├── article.js    # 文章模型
│   │   │   └── comment.js    # 评论模型
│   │   └── repositories/
│   │       ├── user-repo.js   # 用户仓库
│   │       ├── article-repo.js # 文章仓库
│   │       └── comment-repo.js # 评论仓库
│   └── services/
│       ├── blog-service.js    # 博客服务
│       └── index.js          # 服务入口
├── test/
│   ├── mongodb/
│   │   ├── user.test.js      # 用户测试
│   │   ├── article.test.js   # 文章测试
│   │   └── comment.test.js   # 评论测试
│   └── postgresql/
│       ├── user.test.js      # 用户测试
│       ├── article.test.js   # 文章测试
│       └── comment.test.js   # 评论测试
├── package.json
└── README.md

安装依赖

bash
npm install

运行测试

bash
npm test

核心功能

1. MongoDB 集成

实现 MongoDB 连接、模型定义和 CRUD 操作。

2. PostgreSQL 集成

实现 PostgreSQL 连接、模型定义和 CRUD 操作。

3. 数据访问层

实现统一的 Repository 模式,支持两种数据库。

4. 业务服务层

实现博客系统的业务逻辑。

使用示例

使用 MongoDB

javascript
const { BlogService } = require('./src/services');

const service = new BlogService('mongodb');

// 创建用户
const user = await service.createUser({
  name: '张三',
  email: 'zhangsan@example.com'
});

// 创建文章
const article = await service.createArticle({
  title: '我的第一篇文章',
  content: '这是文章内容',
  authorId: user.id
});

// 添加评论
const comment = await service.createComment({
  content: '很好的文章',
  articleId: article.id,
  userId: user.id
});

使用 PostgreSQL

javascript
const { BlogService } = require('./src/services');

const service = new BlogService('postgresql');

// 创建用户
const user = await service.createUser({
  name: '张三',
  email: 'zhangsan@example.com'
});

// 创建文章
const article = await service.createArticle({
  title: '我的第一篇文章',
  content: '这是文章内容',
  authorId: user.id
});

// 添加评论
const comment = await service.createComment({
  content: '很好的文章',
  articleId: article.id,
  userId: user.id
});

可扩展功能点

1. 分页功能

在 Repository 层添加分页支持:

javascript
// TODO: 实现分页查询
async findPaginated(conditions, options) {
  const { page = 1, pageSize = 10 } = options;
  const skip = (page - 1) * pageSize;
  
  const [data, total] = await Promise.all([
    this.findAll({ where: conditions, skip, limit: pageSize }),
    this.count(conditions)
  ]);
  
  return {
    data,
    pagination: {
      page,
      pageSize,
      total,
      totalPages: Math.ceil(total / pageSize)
    }
  };
}

2. 搜索功能

添加全文搜索支持:

javascript
// TODO: 实现搜索功能
async search(keyword) {
  // MongoDB: 使用 $text 操作符
  // PostgreSQL: 使用 tsvector 和 to_tsquery
}

3. 缓存层

集成 Redis 缓存:

javascript
// TODO: 实现缓存层
class CachedRepository {
  constructor(repository, cache) {
    this.repository = repository;
    this.cache = cache;
  }
  
  async findOne(conditions) {
    const cacheKey = JSON.stringify(conditions);
    const cached = await this.cache.get(cacheKey);
    
    if (cached) return JSON.parse(cached);
    
    const result = await this.repository.findOne(conditions);
    await this.cache.set(cacheKey, JSON.stringify(result), 'EX', 300);
    
    return result;
  }
}

4. 数据迁移

实现数据库版本管理:

javascript
// TODO: 实现数据迁移
class Migration {
  async up() {
    // 执行迁移
  }
  
  async down() {
    // 回滚迁移
  }
}

5. 连接池优化

优化数据库连接管理:

javascript
// TODO: 实现连接池监控
class ConnectionPool {
  constructor(config) {
    this.pool = new Pool(config);
    this.stats = {
      total: 0,
      active: 0,
      idle: 0
    };
  }
  
  async connect() {
    this.stats.total++;
    this.stats.active++;
    const client = await this.pool.connect();
    this.stats.active--;
    this.stats.idle++;
    
    return client;
  }
  
  release(client) {
    this.stats.idle--;
    this.pool.release(client);
  }
}

下一步

查看 05-lesson-plan.md 了解详细的课程计划。


架构师AI杜公众号二维码

扫描二维码关注"架构师AI杜"公众号,获取更多技术内容和最新动态