将 Mongoose 与 Next.js 一起使用
¥Using Mongoose With Next.js
Next.js 是一个流行的框架,用于使用 React 构建全栈应用。Mongoose 与 Next.js 一起开箱即用。如果你想开始使用,请使用 Next.js 的官方 Mongoose 示例应用。此外,如果你将 Next.js 与 Vercel 无服务器函数 一起使用,请查看 Mongoose 的 AWS Lambda 文档。
¥Next.js is a popular framework for building full stack applications with React. Mongoose works out of the box with Next.js. If you're looking to get started, please use Next.js' official Mongoose sample app. Furthermore, if you are using Next.js with Vercel Serverless Functions, please review Mongoose's AWS Lambda docs.
使用 Next.js 时有一些你应该注意的常见问题。
¥There are a few common issues when working with Next.js that you should be aware of.
类型错误:无法读取未定义的属性(读取 'prototype')
¥TypeError: Cannot read properties of undefined (reading 'prototype')
你可以通过将以下内容添加到 next.config.js
来解决此问题:
¥You can fix this issue by adding the following to your next.config.js
:
const nextConfig = {
experimental: {
esmExternals: "loose", // <-- add this
serverComponentsExternalPackages: ["mongoose"] // <-- and this
},
// and the following to enable top-level await support for Webpack
webpack: (config) => {
config.experiments = {
topLevelAwait: true
};
return config;
},
}
此问题是由 MongoDB 的 bson 解析器的这一变化 引起的。MongoDB 的 bson 解析器在 ESM 结构下使用顶层等待和动态导入来避免一些 Webpack 打包问题。Next.js 强制使用 ESM 结构。
¥This issue is caused by this change in MongoDB's bson parser. MongoDB's bson parser uses top-level await and dynamic import in ESM mode to avoid some Webpack bundling issues. And Next.js forces ESM mode.
Next.js 边缘运行时
¥Next.js Edge Runtime
Mongoose 目前不支持 Next.js 边缘运行时。虽然你可以在 Edge Runtime 中导入 Mongoose,但你将获得 Mongoose 的浏览器库。Mongoose 无法在 Edge Runtime 中连接到 MongoDB,因为 Edge Runtime 目前不支持 Node.js net
API,这是 MongoDB Node 驱动程序用来连接到 MongoDB 的。
¥Mongoose does not currently support Next.js Edge Runtime.
While you can import Mongoose in Edge Runtime, you'll get Mongoose's browser library.
There is no way for Mongoose to connect to MongoDB in Edge Runtime, because Edge Runtime currently doesn't support Node.js net
API, which is what the MongoDB Node Driver uses to connect to MongoDB.