在 Vercel 和 Netlify 上部署 next.js 项目时如何解决 Runtime.UnhandledPromiseRejection 错误?

How to resolve Runtime.UnhandledPromiseRejection error while deploying the next.js project on Vercel and Netlify?

我在 Vercel / Netlify 上部署时收到此错误。 部署时 Vercel 和 Netlify 收到相同的错误。 解决此问题的任何步骤都会有所帮助。

数据库代码:

import mongoose from 'mongoose';

const connection = {};

async function connect() {
  if (connection.isConnected) {
    console.log('already connected');
    return;
  }
  if (mongoose.connections.length > 0) {
    connection.isConnected = mongoose.connections[0].readyState;
    if (connection.isConnected === 1) {
      console.log('use previous connection');
      return;
    }
    await mongoose.disconnect();
  }
  const db = await mongoose.connect(process.env.MONGODB_URI, {
    // useNewUrlParser: true,
    // useUnifiedTopology: true,
  });
  console.log('new connection');
  connection.isConnected = db.connections[0].readyState;
}

async function disconnect() {
  if (connection.isConnected) {
    if (process.env.NODE_ENV === 'production') {
      await mongoose.disconnect();
      connection.isConnected = false;
    } else {
      console.log('not disconnected');
    }
  }
}

function convertDocToObj(doc) {
  doc._id = doc._id.toString();
  doc.createdAt = doc.createdAt.toString();
  doc.updatedAt = doc.updatedAt.toString();
  return doc;
}

const db = { connect, disconnect, convertDocToObj };
export default db;

错误截图

错误:

({"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"MongooseError: The uriparameter toopenUri()must be a string, got \"undefined\". Make sure the first parameter tomongoose.connect()ormongoose.createConnection()is a string.","trace":["Runtime.UnhandledPromiseRejection: MongooseError: Theuriparameter toopenUri()must be a string, got \"undefined\". Make sure the first parameter tomongoose.connect()ormongoose.createConnection() is a string."," at process.<anonymous> (/var/runtime/index.js:35:15)"," at process.emit (events.js:314:20)"," at processPromiseRejections (internal/process/promises.js:209:33)"," at processTicksAndRejections (internal/process/task_queues.js:98:32)"]})

1)从 mongoDB.In 您的 .env 文件中检查您的连接字符串,并将其与来自地图集的数据进行比较

您的用户是正确的吗? 您的 密码 正确吗? 你的 cluster 名称是一样的吗? 你的数据库名称是一样的吗?

1a)确保您的 .env 在根文件夹中!

2) 在mongoDB Atlas 中检查网络访问IP。活跃吗?如果没有,建立新的。

3)如果您正在使用 VPN,请将其关闭。

4) 最后 => https://vercel.com/docs/concepts/projects/environment-variables

希望对您有所帮助!祝你好运;-)