'NextJS: load global plugin in Mongoose before model creation

I have a folder structure looking something like this

root/
  pages/
  models/
    User.js
  utils/
    plugin.js
    dbConnect.js

I want to be able to load the global plugin /utils/plugin.js before my model creation. However, in nextjs, the model is created before the plugin is installed. Is there a way to ensure that the global plugin is installed before model creation?

dbConnect.js is copied from next.js/examples/with-mongodb-mongoose

// dbConnect.js
import mongoose from 'mongoose'

// loading global plugin
console.log('loading plugin')
mongoose.plugin(require('./plugin'))

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 = {
      bufferCommands: false,
    }

    cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
      return mongoose
    })
  }
  cached.conn = await cached.promise
  return cached.conn
}

export default dbConnect
// User.js
import { Schema, model } from 'mongoose'

const UserSchema = new Schema({
  firstName: String,
  lastName: String,
})

console.log('creating user model')
export default model('User', UserSchema)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source