Download api/lib/db/connectDb.js from Zhitomir/chat: direct link, hf CLI and curl.
- Browser
- Download file 1.16 kB
-
https://huggingface.co/spaces/Zhitomir/chat/resolve/main/api/lib/db/connectDb.js
- Command line
-
hf download hf://spaces/Zhitomir/chat/api/lib/db/connectDb.js
-
curl -L -o connectDb.js https://huggingface.co/spaces/Zhitomir/chat/resolve/main/api/lib/db/connectDb.js
1.16 kB
| require('dotenv').config(); | |
| const mongoose = require('mongoose'); | |
| const MONGO_URI = process.env.MONGO_URI; | |
| if (!MONGO_URI) { | |
| throw new Error('Please define the MONGO_URI environment variable'); | |
| } | |
| /** | |
| * 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.mongoose; | |
| if (!cached) { | |
| cached = global.mongoose = { conn: null, promise: null }; | |
| } | |
| async function connectDb() { | |
| if (cached.conn && cached.conn?._readyState === 1) { | |
| return cached.conn; | |
| } | |
| const disconnected = cached.conn && cached.conn?._readyState !== 1; | |
| if (!cached.promise || disconnected) { | |
| const opts = { | |
| useNewUrlParser: true, | |
| useUnifiedTopology: true, | |
| bufferCommands: false, | |
| // bufferMaxEntries: 0, | |
| // useFindAndModify: true, | |
| // useCreateIndex: true | |
| }; | |
| mongoose.set('strictQuery', true); | |
| cached.promise = mongoose.connect(MONGO_URI, opts).then((mongoose) => { | |
| return mongoose; | |
| }); | |
| } | |
| cached.conn = await cached.promise; | |
| return cached.conn; | |
| } | |
| module.exports = connectDb; | |