我正在尝试设置MongoDB连接库函数。我知道此函数很稳定,它在许多地方都被使用(搜索这里使用全局变量来保持跨热重载的缓存连接),包括next.js发布等许多用途。请注意,将数据库连接存储在全局中的目的是减少同时使用的数据库连接总数。
我不明白的是,当我通过
database.js
错误信息:
注意,我在我的生成的 SvelteKit 最小化存储库中看到了一个名为
有什么想法导致这个错误吗?
参考:"@sveltejs/kit": "version": "1.0.0-next.118"
编辑:在处理这个问题的过程中,花费了很多时间,全局未定义的错误似乎来自于"import { MongoClient } from" mongodb"; 如果我添加适当的console.logs,我可以看到MongoClient函数在服务器上运行正常,但是在客户端上出现全局错误。服务器没有任何错误提示。
我不明白的是,当我通过
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函数在服务器上运行正常,但是在客户端上出现全局错误。服务器没有任何错误提示。