Sveltekit 在部署到 Vercel 时失去与 MongoDB 的连接

编程入门 行业动态 更新时间:2024-10-04 17:29:42

<a href=https://www.elefans.com/category/jswz/34/1771340.html style=Sveltekit 在部署到 Vercel 时失去与 MongoDB 的连接"/>

Sveltekit 在部署到 Vercel 时失去与 MongoDB 的连接

我最近在 svelte.config.js 中使用

@sveltejs/adapter-vercel
适配器向 Vercel 部署了一个小型 SvelteKit 网络应用程序,如下所示:

import adapter from '@sveltejs/adapter-vercel';

const config = {
    kit: {
        adapter: adapter(),
    },
};

作为数据库,我使用 MongoDB(托管在 Atlas 免费集群上)。问题是有时(看似随机)无法再访问数据库并抛出以下错误:

MongoTopologyClosedError: Topology is closed
    at processWaitQueue (/var/task/node_modules/mongodb/lib/sdam/topology.js:513:46)
    at Topology.selectServer (/var/task/node_modules/mongodb/lib/sdam/topology.js:282:9)
    at Topology.<anonymous> (/var/task/node_modules/mongodb/lib/sdam/topology.js:41:94)
    at node:internal/util:375:7
    at new Promise (<anonymous>)
    at Topology.selectServerAsync (node:internal/util:361:12)
    at executeOperationAsync (/var/task/node_modules/mongodb/lib/operations/execute_operation.js:74:35)
    at /var/task/node_modules/mongodb/lib/operations/execute_operation.js:12:45
    at maybeCallback (/var/task/node_modules/mongodb/lib/utils.js:263:21)
    at executeOperation (/var/task/node_modules/mongodb/lib/operations/execute_operation.js:12:38)

在做了一些研究之后,我不清楚到底是什么导致了这个错误。这就是我连接到数据库的方式:

import { MongoClient } from 'mongodb';

const client = new MongoClient(PRIVATE_DB_CONNECTION_STRING);
const db = client.db();

export async function connectToDatabase() {
    try {
        await client.connect();
        console.log('Connected to mongodb');
    } catch (error) {
        console.log(error);
    }
}

export const myCollection = db.collection('randomCollection');

connectToDatabase()
方法在应用程序启动时在
hooks.server.ts
中调用。 有谁知道什么可能导致这个错误以及如何摆脱它?

回答如下:

更多推荐

Sveltekit 在部署到 Vercel 时失去与 MongoDB 的连接

本文发布于:2024-05-30 22:24:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770988.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Sveltekit   Vercel   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!