NextJS API使用顶层await报错 如何共享MongoDB集合实例避免重复代码
解决方案
最佳实践:使用MongoDB连接单例模式
这种方案不需要开启实验特性,适配Next.js运行机制,还能避免重复代码,是更稳妥的选择。
第一步:抽离公共数据库连接工具
新建lib/mongodb.js文件,封装连接逻辑和集合获取方法:
import { MongoClient } from 'mongodb' const uri = process.env.MONGODB_URI const options = {} let client let clientPromise let scheduledCollection if (!process.env.MONGODB_URI) { throw new Error('请在环境变量中配置MONGODB_URI') } // 开发环境下复用全局连接,避免热重载导致连接泄漏 if (process.env.NODE_ENV === 'development') { if (!global._mongoClientPromise) { client = new MongoClient(uri, options) global._mongoClientPromise = client.connect() } clientPromise = global._mongoClientPromise } else { client = new MongoClient(uri, options) clientPromise = client.connect() } // 仅首次调用会初始化集合实例,后续调用直接返回缓存结果 export async function getScheduledCollection() { if (scheduledCollection) return scheduledCollection const client = await clientPromise const db = client.db() scheduledCollection = db.collection('scheduled') return scheduledCollection }
第二步:在API路由中调用
无需把工具函数放到handler内部,所有需要用到scheduled集合的异步函数直接调用封装好的方法即可:
import { getScheduledCollection } from '@/lib/mongodb' export default async function handler(req, res) { await otherFunctionCalls() // 其他业务逻辑 } const otherFunctionCalls = async () => { const scheduled = await getScheduledCollection() // 直接使用scheduled操作数据库 }
可选方案:开启顶层await特性
如果确实想在顶层声明scheduled常量,可以在next.config.js中开启对应的实验特性:
/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { topLevelAwait: true } } module.exports = nextConfig
该方案配置简单,但属于实验特性,稳定性比单例模式差,生产环境更推荐第一种方案。
内容的提问来源于stack exchange,提问作者user1452062
相关产品推荐
相关产品推荐

