Next.js 13.3中使用Mongoose插入MongoDB记录报错求助
Next.js 13.3 + Mongoose + MongoDB 兼容问题与报错处理
问题说明
在Next.js 13.3项目中,使用Mongoose定义的User Schema向MongoDB保存记录时触发两个问题:
- 编译报错:
Module not found: Can't resolve 'mongodb-client-encryption' - POST请求返回500内部服务器错误
同时需要确认Mongoose、MongoDB Client与Next.js 13.3的兼容性。
报错信息
Module not found: Can't resolve 'mongodb-client-encryption' in 'J:\react-projecte\find\node_modules\mongoose\node_modules\mongodb\lib'
POST http://localhost:3000/api/generate 500 (Internal Server Error)
项目代码片段
app/models/User/page.tsx
import { Schema, model, models } from "mongoose"; const userSchema = new Schema({ name: String, email: { type: String, required: true, unique: true, }, }); const User = models.User || model("User", userSchema); export default User;
app/api/generate/route.ts
export async function POST(request:Request ) { const client = await clientPromise; const db = client.db("generate"); console.log('CREATING DOCUMENT'); db.collection("singleUser").insertOne( await new User({name:"Benij",email:"max.mustermann@gmx.de"})) console.log('CREATING DONE'); }
next.config.js
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { // this will override the experiments config.experiments = { ...config.experiments, topLevelAwait: true }; // this will just update topLevelAwait property of config.experiments // config.experiments.topLevelAwait = true return config; }, reactStrictMode: true, images: { remotePatterns: [ { protocol: "https", hostname: "replicate.com", }, { protocol: "https", hostname: "replicate.delivery", }, ], }, experimental: { appDir: true, }, }; module.exports = nextConfig;
/lib/mongodb.ts
import { MongoClient } from "mongodb"; if (!process.env.MONGODB_URI) { throw new Error('Invalid/Missing environment variable: "MONGODB_URI"'); } const uri = process.env.MONGODB_URI; const options = {}; let client; let clientPromise: Promise<MongoClient>; 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 default clientPromise;
解决方案
1. 兼容性确认
Mongoose、MongoDB Client与Next.js 13.3完全兼容,报错属于依赖缺失或代码逻辑混用问题,并非框架不兼容。
2. 解决mongodb-client-encryption缺失问题
执行以下命令安装缺失的依赖包:
npm install mongodb-client-encryption # 或使用yarn yarn add mongodb-client-encryption
若安装后仍报错,建议检查Mongoose与MongoDB的版本兼容性(例如Mongoose 7.x需搭配MongoDB 5.x+),可在package.json中锁定兼容版本。
3. 修正代码逻辑错误
当前API路由同时混用了原生MongoDB Client和Mongoose模型,导致逻辑混乱,需统一使用一种操作方式:
方式一:使用Mongoose模型保存
- 首先修改模型文件路径:将
app/models/User/page.tsx重命名为app/models/User.ts(避免与Next.js路由组件冲突) - 调整API路由代码:
import connectDB from '@/lib/mongoose'; import User from '@/app/models/User'; export async function POST(request: Request) { try { // 建立Mongoose连接 await connectDB(); console.log('CREATING DOCUMENT'); const newUser = await User.create({ name: "Benij", email: "max.mustermann@gmx.de" }); console.log('CREATING DONE'); return new Response(JSON.stringify(newUser), { status: 201 }); } catch (error) { console.error('创建用户失败:', error); return new Response(JSON.stringify({ error: '创建用户失败' }), { status: 500 }); } }
- 新增Mongoose连接文件
/lib/mongoose.ts:
import mongoose from 'mongoose'; const connectDB = async () => { // 若已连接则直接返回 if (mongoose.connection.readyState === 1) { return mongoose.connection.asPromise(); } // 建立新连接 return await mongoose.connect(process.env.MONGODB_URI!); }; export default connectDB;
方式二:使用原生MongoDB Client保存(无需Mongoose)
直接用原生Client插入文档,不需要依赖Mongoose模型:
import clientPromise from '@/lib/mongodb'; export async function POST(request: Request) { try { const client = await clientPromise; const db = client.db("generate"); console.log('CREATING DOCUMENT'); const result = await db.collection("singleUser").insertOne({ name: "Benij", email: "max.mustermann@gmx.de" }); console.log('CREATING DONE'); return new Response(JSON.stringify(result), { status: 201 }); } catch (error) { console.error('创建文档失败:', error); return new Response(JSON.stringify({ error: '创建文档失败' }), { status: 500 }); } }
4. 其他注意事项
- 确保
process.env.MONGODB_URI环境变量已正确配置在.env.local文件中 - API路由需返回合法的Response对象,避免因未返回响应导致的500错误
内容的提问来源于stack exchange,提问作者Captai-N
相关产品推荐
相关产品推荐

