SvelteKit和MongoDB参考错误:未定义global

3
我正在尝试设置MongoDB连接库函数。我知道此函数很稳定,它在许多地方都被使用(搜索这里使用全局变量来保持跨热重载的缓存连接),包括next.js发布等许多用途。请注意,将数据库连接存储在全局中的目的是减少同时使用的数据库连接总数。
我不明白的是,当我通过import { connectToDatabase } from '$lib/database';导入此库时,我得到的错误是什么。
database.js
// https://github.com/mongodb-developer/mongodb-next-todo/blob/main/util/mongodb.js
import { ENV_OBJ } from "$lib/env";
import { MongoClient } from "mongodb";

const uri = ENV_OBJ.MONGODB_URI;

if (!uri) {
    throw new Error("Please define the Mongodb uri environment variable inside .env");
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */
let cached = global.mongo

if (!cached) {
    cached = global.mongo = { conn: null, promise: null }
}

export const connectToDatabase = async() => {
    if (cached.conn) {
        return cached.conn;
    }

    if (!cached.promise) {
        const options = {
            useNewUrlParser: true,
            useUnifiedTopology: true
        };

        cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
            return {
                client,
                db: client.db(MONGODB_DB),
            }
        })
    }
    cached.conn = await cached.promise;
    return cached.conn;
}

错误信息:
global is not defined

ReferenceError: global is not defined
    at node_modules/mongodb/lib/promise_provider.js (http://localhost:3000/node_modules/.vite/mongodb.js?v=3885e04e:548:25)
    at __require2 (http://localhost:3000/node_modules/.vite/chunk-6ODJH7E3.js?v=3885e04e:10:44)
    at node_modules/mongodb/lib/utils.js (http://localhost:3000/node_modules/.vite/mongodb.js?v=3885e04e:6524:30)
    at __require2 (http://localhost:3000/node_modules/.vite/chunk-6ODJH7E3.js?v=3885e04e:10:44)
    at node_modules/mongodb/lib/cursor/abstract_cursor.js (http://localhost:3000/node_modules/.vite/mongodb.js?v=3885e04e:10873:19)
    at __require2 (http://localhost:3000/node_modules/.vite/chunk-6ODJH7E3.js?v=3885e04e:10:44)
    at node_modules/mongodb/lib/index.js (http://localhost:3000/node_modules/.vite/mongodb.js?v=3885e04e:25281:29)
    at __require2 (http://localhost:3000/node_modules/.vite/chunk-6ODJH7E3.js?v=3885e04e:10:44)
    at http://localhost:3000/node_modules/.vite/mongodb.js?v=3885e04e:25616:23

注意,我在我的生成的 SvelteKit 最小化存储库中看到了一个名为 global.d.ts 的文件,但我不确定它的用途。 它仅包含以下内容:
 /// <reference types="@sveltejs/kit" /> 

有什么想法导致这个错误吗?
参考:"@sveltejs/kit": "version": "1.0.0-next.118"
编辑:在处理这个问题的过程中,花费了很多时间,全局未定义的错误似乎来自于"import { MongoClient } from" mongodb"; 如果我添加适当的console.logs,我可以看到MongoClient函数在服务器上运行正常,但是在客户端上出现全局错误。服务器没有任何错误提示。

demo db.js ref1 ref2 - lowtechsun
1个回答

3
原来我在一个不是.js辅助文件或api样式(.js)的端点中调用了import { connectToDatabase } from '$lib/database'。我试图直接从xxx.svelte文件的<script>部分使用该导入并进行数据库调用,但这是绝对行不通的。这会立即生成一个全局未定义错误。请注意保留html标签,此处不需要解释。

我也犯了一个愚蠢的错误。感谢你在这里提醒我... ;) - A. Rabus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接