Koa & Express 连接 MongoDB 实战(短网址跳转示例)
本文整理 Koa/Express 框架通过 MongoClient 连接 MongoDB 的完整实现方案,以「短网址跳转」为核心业务场景,覆盖数据库连接、集合查询、响应处理等核心逻辑,保证代码可直接运行且符合生产环境最佳实践。
一、前置准备
1. 安装依赖
1 2 3 4 5 6 7 8
| npm install mongodb --save
npm install koa koa-router --save
npm install express --save
|
2. 核心说明
- 使用 MongoDB 官方驱动
MongoClient 而非第三方 ORM,轻量且原生;
- 采用单例模式管理数据库连接(避免每次请求重复创建连接,提升性能);
- 异步处理数据库操作(
async/await),适配 Node.js 异步特性。
二、Koa 连接 MongoDB 实现(完整代码)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| const Koa = require('koa'); const Router = require('koa-router'); const { MongoClient } = require('mongodb');
const app = new Koa(); const router = new Router();
const MONGODB_URL = 'mongodb://localhost:27017/short_url';
const mongoClientPromise = MongoClient.connect(MONGODB_URL, { useNewUrlParser: true, useUnifiedTopology: true });
router.get('/:id', async (ctx, next) => { try { const db = await mongoClientPromise; const collection = db.collection('test'); const shortUrlRecord = await collection.findOne({ _id: ctx.params.id });
if (!shortUrlRecord) { ctx.status = 404; ctx.body = { code: 404, msg: '短网址不存在' }; } else { ctx.redirect(shortUrlRecord.url); } } catch (err) { ctx.status = 500; ctx.body = { code: 500, msg: '服务器错误', error: err.message }; } });
app.use(router.routes()).use(router.allowedMethods()); app.listen(3000, () => { console.log('Koa 服务启动:http://localhost:3000'); });
|
三、Express 连接 MongoDB 实现(对应逻辑)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| const express = require('express'); const { MongoClient } = require('mongodb');
const app = express(); const router = express.Router();
const MONGODB_URL = 'mongodb://localhost:27017/short_url'; const mongoClientPromise = MongoClient.connect(MONGODB_URL, { useNewUrlParser: true, useUnifiedTopology: true });
router.get('/:id', async (req, res) => { try { const db = await mongoClientPromise; const collection = db.collection('test'); const shortUrlRecord = await collection.findOne({ _id: req.params.id });
if (!shortUrlRecord) { res.status(404).json({ code: 404, msg: '短网址不存在' }); } else { res.redirect(shortUrlRecord.url); } } catch (err) { res.status(500).json({ code: 500, msg: '服务器错误', error: err.message }); } });
app.use(router); app.listen(3001, () => { console.log('Express 服务启动:http://localhost:3001'); });
|
四、关键逻辑解析
1. 数据库连接优化
MongoClient.connect 返回 Promise,提前执行并缓存为 mongoClientPromise,实现连接复用(生产环境禁止每次请求都调用 connect,会导致连接池耗尽);
- 连接配置中
useNewUrlParser 和 useUnifiedTopology 是兼容 MongoDB 新版本的必要配置(避免控制台警告)。
2. 核心业务逻辑
- 通过
ctx.params.id(Koa)/req.params.id(Express)获取 URL 中的短网址 ID;
collection.findOne() 异步查询 MongoDB 集合,匹配 _id 字段;
- 无匹配记录返回 404,有记录则通过
redirect 跳转到目标 URL。
3. 异常处理
- 包裹
try/catch 捕获数据库操作异常,避免服务崩溃;
- 异常时返回 500 状态码并携带错误信息,便于排查问题。
五、扩展说明
- 集合操作扩展:除了
findOne,可根据业务需求使用 insertOne(新增短网址)、updateOne(更新)、deleteOne(删除)等方法;
- 连接关闭:若服务停止,可通过
db.close() 手动关闭数据库连接;
- 生产环境优化:
- 把 MongoDB 地址配置到环境变量(如
process.env.MONGODB_URL),避免硬编码;
- 添加连接超时配置(
connectTimeoutMS: 5000),防止连接阻塞。
总结
- Koa/Express 连接 MongoDB 的核心是复用
MongoClient 连接,通过 async/await 处理异步操作;
- 业务逻辑中需区分框架的请求/响应对象(Koa 用
ctx,Express 用 req/res);
- 必须添加异常处理和状态码响应,保证服务稳定性。