Next.js 在使用pages API时,NextJS不断创建到MongoDB的新连接

Next.js 在使用pages API时,NextJS不断创建到MongoDB的新连接,next.js,Next.js,我一直在关注NextJS的官方Github页面,我已经成功地启动并运行了我的项目 以下是我的文件结构: Each API route is a lambda so each one has its own stateTLDR; consts are block scoped.(connectionObject) As per Mozilla const documentation Constants are block-scoped, much like variables defined us

我一直在关注NextJS的官方Github页面,我已经成功地启动并运行了我的项目

以下是我的文件结构:

Each API route is a lambda so each one has its own state

TLDR; consts are block scoped.(connectionObject)

As per Mozilla const documentation Constants are block-scoped, much like variables defined using the let keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared

So in your case connectionObject remains empty because it's Chang's scope where you update this is block. Hence outside the block it is empty.

Best example to verify is first code snippet in above documentation

const number = 42;

try {
  number = 99;
} catch (err) {
  console.log(err);
  // expected output: TypeError: invalid assignment to const `number'
  // Note - error messages will vary depending on browser
}

console.log(number);
// expected output: 42

每个API路由都是lambda,因此每个路由都有自己的状态

TLDR;常量是块作用域。(connectionObject)

依照 常量是块范围的,很像使用let关键字定义的变量。常量的值不能通过重新分配来更改,也不能重新声明

所以在您的例子中,connectionObject保持为空,因为它是Chang的作用域,您可以在其中更新此is块。因此,在街区外,它是空的

要验证的最佳示例是上述文档中的第一个代码段

const number=42;
试一试{
数字=99;
}捕捉(错误){
控制台日志(err);
//预期输出:TypeError:对常量'number'的赋值无效
//注意-错误消息因浏览器而异
}
控制台日志(编号);
//预期产出:42

我将
connectDb
函数更改为常规函数,但没有修复它。每条路线似乎都有自己的路线state@MikeK我不是这个意思。您可以将每个API路由(文件)想象为一个服务器。所以,有两个API路由就像运行两台服务器,每台服务器都有自己的全局状态,我知道,但有可能以某种方式修复这个问题吗?我使用了一个定制服务器而不是他们的PagesAPI,但我无法以这种方式部署到Vercel。只有当我使用他们的内置页面API时,才支持部署到Vercel,但这里的缺点是,正如您所说,每个文件都有自己的状态。那么我的选择是什么?@MikeK最好是使用另一个平台,比如Heroku。但是,如果您仍然想使用Vercel,您可以创建一个特殊的API路由来保存您的状态,您可以从其他路由向它发出请求以获取这些状态,或者尝试使用连接池更新它们?编辑:没关系,我知道你在找什么了