mongodb - 将 mongodb 集成到现有 NextJS(TS) 应用程序“找不到模块:无法解析 'dns'”
问题描述
我正在尝试集成mongodb
到我的 NextTS 应用程序中,但我遇到了问题,我无法弄清楚。
到目前为止我做了什么:
我创建了两个过程变量MONGODB_URI
和MONGODB_DB
我mongodb.ts
在该utils
文件夹下创建了以下内容,这些内容来自 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
解决方案
我只是跑了npm install dns
,因为似乎包中缺少依赖项。
推荐阅读
- c# - HTML.ActionLink 到详细信息页面不起作用
- c# - 如何在richTextBox 中添加图像?
- postgresql - 使用 JPA 调用原生 Postgresql 命令
- r - 读取单独的文本文件并将它们作为单独的数据框保存在单个变量中
- android - 谷歌地图没有故意丢针
- html - 从网页调用 Node.js 函数
- python - 带有字符串变量字段的 Django 过滤器
- javascript - IE11 中未处理的承诺拒绝 InvalidCharacterError 与 VEE Validate Vue.js 和 babel-polyfill
- javascript - 错误 - [JSC_UNDEFINED_VARIABLE] 变量 previousPage 未声明 - Google Closure Compiler
- javascript - 如何在wordpress上自动完成输入和API url?