Last active
October 12, 2022 19:22
-
-
Save codewithleader/bf10ca4a24aa565c8eb3aefb64b934bf to your computer and use it in GitHub Desktop.
Next.js - Mongo + Mongoose connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import mongoose from 'mongoose'; | |
| /** | |
| * 0 = disconnected | |
| * 1 = connected | |
| * 2 = connecting | |
| * 3 = disconnecting | |
| */ | |
| const mongoConnection = { | |
| isConnected: 0, | |
| }; | |
| export const connect = async () => { | |
| if (mongoConnection.isConnected) { | |
| console.log('We were already connected to the database'); | |
| return; | |
| } | |
| if (mongoose.connections.length > 0) { | |
| mongoConnection.isConnected = mongoose.connections[0].readyState; | |
| if (mongoConnection.isConnected === 1) { | |
| console.log('Using previous connection'); | |
| return; | |
| } | |
| await mongoose.disconnect(); | |
| } | |
| await mongoose.connect(process.env.MONGO_URL || ''); | |
| mongoConnection.isConnected = 1; | |
| console.log('Connected to MongoDB:', process.env.MONGO_URL); | |
| }; | |
| export const disconnect = async () => { | |
| if (process.env.NODE_ENV === 'development') return; | |
| if (mongoConnection.isConnected === 0) return; | |
| await mongoose.disconnect(); | |
| mongoConnection.isConnected = 0; | |
| console.log('Disconnected from MongoDB'); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment