English 中文(简体)
Intermittent Unhandled Promise Rejection - MongoServerSelection rror:链接时间
原标题:Intermittent Unhandled Promise Rejection - MongoServerSelectionError: connection timed out

I am getting below error randomly. Here is my stack

  • App deployed on vercel is talking to Atlas mongodb (free tier)
  • Nodejs - 18.16.1
  • nextjs 13
  • mongodb package version - 5.8.1
ERROR   Unhandled Promise Rejection     {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"MongoServerSelectionError: connection timed out","reason":{"errorType":"MongoServerSelectionError","errorMessage":"connection timed out","reason":{"type":"ReplicaSetNoPrimary","servers":{},"stale":false,"compatible":true,"heartbeatFrequencyMS":10000,"localThresholdMS":15,"setName":"Cluster0-shard-0","maxElectionId":null,"maxSetVersion":null,"commonWireVersion":0,"logicalSessionTimeoutMinutes":null},"stack":["MongoServerSelectionError: connection timed out","    at Timeout._onTimeout (/var/task/node_modules/mongodb/lib/sdam/topology.js:278:38)","    at listOnTimeout (node:internal/timers:569:17)","    at process.processTimers (node:internal/timers:512:7)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: MongoServerSelectionError: connection timed out","    at process.<anonymous> (file:///var/runtime/index.mjs:1186:17)","    at process.emit (node:events:525:35)","    at emit (node:internal/process/promises:149:20)","    at processPromiseRejections (node:internal/process/promises:283:27)","    at process.processTicksAndRejections (node:internal/process/task_queues:96:32)"]}
[ERROR] [1692852863980] LAMBDA_RUNTIME Failed to post handler success response. Http response code: 400.
RequestId: 971d9da3-a51d-4511-a561-22d5702be848 Error: Runtime exited with error: exit status 128

当出现这一错误时,服务器用500个错误代码对。

谁能告诉我为什么会发生这种情况? 这是否归因于Atlas Mongodb的自由等级?

Below code shows how I am connecting to mongodb. Clientpromise is being imported and then used to do db operations in other files.

import { MongoClient } from "mongodb";

//mongodb+srv://sjhfjhfjhf/ongodb.net/awesomedb?serverSelectionTimeoutMS=60000
const uri = process.env.MONGODB_URI;
const options = {
  //useUnifiedTopology: true,
  useNewUrlParser: true,
  serverSelectionTimeoutMS: 59000,
};

let client;
let clientPromise;

if (!process.env.MONGODB_URI) {
  throw new Error("Please add your Mongo URI to .env.local");
}

if (process.env.NODE_ENV === "development") {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options);
    global._mongoClientPromise = client.connect();
  }
  clientPromise = global._mongoClientPromise;
} else {
  // In production mode, it s best to not use a global variable.
  client = new MongoClient(uri, options);
  clientPromise = client.connect();
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;

在这里,我是如何问答。


import { ObjectId } from  mongodb ;
import clientPromise from  ../../lib/mongodb 
import { connectToDatabase, slugify } from  ./blog ;

export async function saveAdToMongoDB(adObj) {
  try {
    const collection = (await clientPromise).db().collection("ads");  
    let catslug = slugify(adObj.businessCategory)
    let slug = slugify( adObj.businessName + "-" + adObj.city + "-" + catslug)
    adObj.slug = slug ;
    adObj.catslug = catslug;
    let advertisementObject = {...adObj, status:"pending",image:""}
    let result = await collection.insertOne(advertisementObject);
  } catch (err) {
    console.error("Failed to save ad to MongoDB:", err);
  } 
}

我升级了青ongo素包和 next子包,但没有帮助。 互联网上的其他解决办法大多涉及防火墙和白化。 但我认为这不会引起这一问题。

问题回答

它综合了免费Atlas级和Vercel托管的局限性。

当你耗尽500个连接配额时,你就获得连接时间。 见。 页: 1

我的错误与你相同,并且能够用从Vercel的“mongodb-starter repo”中提取的“密码”替换来加以固定。

https://github.com/vercel/mongodb-starter/blob/main/lib/mongodb.ts

我以前曾与你一样拥有同样的<代码>clientPromise,但自从我对单一州办法进行更新以来,我没有看到我的韦克尔生产部署的错误。

希望这一帮助,我刚刚签署,希望能拯救我花在解决这个问题的一天的人。





相关问题
Access DB Ref MongoDB

Whats the best way to access/query a DB Ref: UPDATE: users: name, groupref : {$ref:"groups",$id:"ObjectId ..." } } groups: name, topic, country,...,.. Assumption is that user belongs to only one ...

MongoDB nested sets

What re the best practices to store nested sets (like trees of comments) in MongoDB? I mean, every comment can have a parent comment and children-comments (answers). Storing them like this: { ...

MongoMapper and migrations

I m building a Rails application using MongoDB as the back-end and MongoMapper as the ORM tool. Suppose in version 1, I define the following model: class SomeModel include MongoMapper::Document ...

MongoDB takes long for indexing

I have the following setup: Mac Pro with 2 GB of RAM (yes, not that much) MongoDB 1.1.3 64-bit 8 million entries in a single collection index for one field (integer) wanted Calling .ensureIndex(...) ...

Storing and accessing large amounts of data

My application creates pieces of data that, in xml, would look like this: <resource url="someurl"> <term> <name>somename</name> <frequency>somenumber</...

热门标签