首页 > 解决方案 > 将 mongodb 集成到现有 NextJS(TS) 应用程序“找不到模块:无法解析 'dns'”

问题描述

我正在尝试集成mongodb到我的 NextTS 应用程序中,但我遇到了问题,我无法弄清楚。

到目前为止我做了什么:

我创建了两个过程变量MONGODB_URIMONGODB_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

标签: mongodbnext.js

解决方案


我只是跑了npm install dns,因为似乎包中缺少依赖项。


推荐阅读