【问题标题】:Integrating mongodb within existing NextJS(TS) app "Module not found: Can't resolve 'dns'"将 mongodb 集成到现有 NextJS(TS) 应用程序“找不到模块:无法解析 'dns'”
【发布时间】: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

【问题讨论】:

标签: mongodb next.js


【解决方案1】:

我刚刚运行了npm install dns,因为似乎包中缺少依赖项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-01
    • 2019-02-21
    • 2021-05-17
    • 2022-12-26
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    相关资源
    最近更新 更多