【发布时间】:2023-03-18 20:30:01
【问题描述】:
我正在尝试将 mongodb 集成到我的 NextTS 应用程序中,但我遇到了问题,我无法解决。
到目前为止我做了什么:
我创建了两个流程变量MONGODB_URI 和MONGODB_DB
我在utils 文件夹下创建了mongodb.ts,其内容来自https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/util/mongodb.js:
import { MongoClient } from "mongodb";
const MONGODB_URI = process.env.MONGODB_URI;
const MONGODB_DB = process.env.MONGODB_DB;
if (!MONGODB_URI) {
throw new Error("Please define the MONGODB_URI environment variable inside .env.local");
}
if (!MONGODB_DB) {
throw new Error("Please define the MONGODB_DB environment variable inside .env.local");
}
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached = global.mongo;
if (!cached) {
cached = global.mongo = { conn: null, promise: null };
}
export async function connectToDatabase() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
return {
client,
db: client.db(MONGODB_DB),
};
});
}
cached.conn = await cached.promise;
return cached.conn;
}
只是为了尝试一下,我已经尝试了示例项目(它只是 JS),它工作得很好yarn create next-app --example with-mongodb with-mongodb-app
当我启动应用程序时,就日志而言,这是中断的地方:
yarn run v1.22.10
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Using webpack 5. Reason: no custom webpack configuration in next.config.js https://nextjs.org/docs/messages/webpack5
error - ./node_modules/mongodb/lib/core/auth/gssapi.js:2:0
Module not found: Can't resolve 'dns'
null
在一个文件中保存后,它会尝试重新编译:
wait - compiling...
info - Using external babel configuration from C:\Users\Darkbound\Desktop\Inventory-ReactTS\.babelrc
error - ./node_modules/mongodb/lib/core/auth/gssapi.js:2:0
Module not found: Can't resolve 'dns'
null
【问题讨论】:
-
我在搜索解决方案时确实阅读了该帖子,但没有,至少我在我的代码中找不到这样的代码。我刚切换到猫鼬,猫鼬工作没有问题。