我用MongoDB连接了下一代。
在我的根目录中,我有/lib/mongodb.ts
,它正确地返回clientPromise
。
然后,在我的/lib/beers.ts
中,我有这个函数:
import clientPromise from "./mongodb";
export const getDbCollection = async (name: string) => {
const client = await clientPromise;
// creates and use a db called "test"
const db = client.db();
const collection = db.collection(name);
return collection;
};
如果我在应用程序中的任何地方导入此函数,它都可以工作。
如果我把这个函数移到另一个位置,比如root/lib/functions.ts
,我的nextjs应用程序就会抛出这个错误
./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0
Module not found: Can't resolve 'dns'
Import trace for requested module:
./node_modules/mongodb/lib/index.js
./lib/mongodb.ts
./lib/functions.ts
./src/components/Dashboard/Dashboard.tsx
./src/components/Dashboard/index.ts
./src/components/Forms/Clients/NewClientForm.tsx
./src/pages/dashboard/clients/new.tsx
https://nextjs.org/docs/messages/module-not-found
我已经试着仔细检查所有这些文件,没有导入问题。
我不明白为什么它会工作在1个文件,而不是其他,在同一个目录?
我试过添加一个next.config.cjs
,但是没有用。
有人知道为什么吗?
1条答案
按热度按时间9vw9lbht1#
这个错误很可能意味着你试图从客户端做一些需要在服务器端做的事情。如果MongoDB模块找不到DNS组件,它就在客户端运行。
因此,在
lib/functions.ts
文件中移动函数时出现此错误的原因很可能是functions.ts
不在服务器上运行,而是在客户端上运行