Created
          August 10, 2021 07:52 
        
      - 
      
- 
        Save skolhustick/fa023be077a41139b830a8f6626ca4f3 to your computer and use it in GitHub Desktop. 
  
    
      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
    
  
  
    
  | // /lib/dbConnect.js | |
| import mongoose from 'mongoose' | |
| /** | |
| Source : | |
| https://github.com/vercel/next.js/blob/canary/examples/with-mongodb-mongoose/utils/dbConnect.js | |
| **/ | |
| const MONGODB_URI = process.env.MONGODB_URI | |
| if (!MONGODB_URI) { | |
| throw new Error( | |
| 'Please define the MONGODB_URI environment variable inside .env.local' | |
| ) | |
| } | |
| /** | |
| * 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 dbConnect () { | |
| if (cached.conn) { | |
| return cached.conn | |
| } | |
| if (!cached.promise) { | |
| const opts = { | |
| useNewUrlParser: true, | |
| useUnifiedTopology: true, | |
| bufferCommands: false, | |
| bufferMaxEntries: 0, | |
| useFindAndModify: true, | |
| useCreateIndex: true | |
| } | |
| cached.promise = mongoose.connect(MONGODB_URI, opts).then(mongoose => { | |
| return mongoose | |
| }) | |
| } | |
| cached.conn = await cached.promise | |
| return cached.conn | |
| } | |
| export default dbConnect | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
I'm getting a 'ReferenceError: global is not defined' error when using this. Both mongodb and mongoose are installed. Any idea which additional package I need?