我正在尝试设置 MongoDB 连接库功能。我知道这个功能很可靠,它用在很多地方(搜索此处使用 Global 来维护跨热重载的缓存连接)并且您会发现很多用途,包括 next.js 版本。请注意,数据库连接全局存储的目的是减少任一时间使用的数据库连接总数。
我不明白的是当我通过导入这个库时遇到的错误import { connectToDatabase } from '$lib/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”:“版本”:“1.0.0-next.118”,
编辑:在这个问题上花了很多时间后,全局未定义错误似乎来自import { MongoClient } from "mongodb";
如果我添加适当的 console.logs,我可以看到 MongoClient 函数在服务器上运行良好,但随后我在客户端上收到全局错误。服务器表明根本没有错误。