简体   繁体   中英

Connecting to MongoDB from Vercel

I have a SvelteKit application deployed on vercel.app that uses a MongoDB (Atlas). In most cases the database connection works, but sometimes I get a connection error (connection timed out).

If this error occurs, and I try again to do something that uses the database, it immeadiately logs the same error again. This problem persists for some time, and then suddendly the database connection works again.

(When running the app locally with "npm run dev", using the same database, I've never experienced this error.)

To connect to the database, I defined:

mongodb-client.ts:

import { MongoClient } from 'mongodb';
const uri = process.env.DB_URI;
const dbClient = new MongoClient(uri).connect();
export default dbClient;

and use it like this (in several places):

import dbClient from '$lib/server/mongodb-client';
const user = await (await dbClient).db().collection('users').findOne({username: username});

I guess that, when the dbClient Promise is rejected (for whatever reason), it stays rejected and any subsequent await will immediately result in "rejected" (and therefore it will not try to reconnect; except that at some point it will...?). Is my understanding correct? How should this be implemented correctly? (Eg Do I need to add some options to the connection URI when this connection is create from a serverless function? Do I need to add some options when creating/connecting the MongoClient? Do I need to do this manually and add a loop, check if the promise is rejected and try again? Or should this be implemented in a completely different way?)

As you probably have guessed I'm new to JavaScript/TypeScript, MongoDB, Serverless and everything... Thanks for any help and advice!

You can declare a function handling the connection to the database.
You will handle connection errors there and also check if a connection is already established:

import { MongoClient } from 'mongodb';

const uri = process.env.DB_URI;
const dbClient = new MongoClient(uri);

export const connectDb = async () => {
  try {
    if (!dbClient.isConnected()) {
      await dbClient.connect();
    }
    return await dbClient.db();
  } catch (e) {
    console.log(e);
    process.exit(1); // Or do something else...
  }
};

Usage:

import { connectDb } from '$lib/server/mongodb-client';

const db = await connectDb();
const user = await db.collection('users').findOne({username: username});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM