Skip to content

Instantly share code, notes, and snippets.

@rashidmya
Last active December 3, 2024 07:49
Show Gist options
  • Save rashidmya/2c075330e636134f00ebe85fbb88fed8 to your computer and use it in GitHub Desktop.
Save rashidmya/2c075330e636134f00ebe85fbb88fed8 to your computer and use it in GitHub Desktop.
nextjs-typescript-mongoose example
import { Mongoose } from 'mongoose';
/* eslint-disable no-var */
declare global {
var mongoose: {
promise: Promise<Mongoose> | null;
conn: Mongoose | null;
};
}
import { models, model, Schema } from 'mongoose';
const UserSchema: Schema = new Schema({
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
displayName: {
type: String,
required: true,
},
role: {
type: String
}
});
const UserModel = models.User || model('User', UserSchema);
export default UserModel
import dbConnect from '@/utils/mongodb';
import UserModel from '@/models/user.model';
// ----------------------------------------------------------------------
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
dbConnect();
const users = UserModel;
const allUsers = await users.find({});
res.status(200).json({ users: allUsers });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Internal server error' });
}
}
import mongoose from 'mongoose';
const { MONGODB_URI, MONGODB_DB } = process.env;
if (!MONGODB_URI) throw new Error('MONGODB_URI not defined');
if (!MONGODB_DB) throw new Error('MONGODB_DB not defined');
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) {
cached.promise = mongoose.connect(`${MONGODB_URI}/${MONGODB_DB}`).then(mongoose => mongoose)
}
cached.conn = await cached.promise;
return cached.conn
}
export default dbConnect;
@ChristopherHButler
Copy link

Thank you for posting your code!

I was thinking you could slim this down a bit by using await in your connect function unless there is some reason you can't?

As an example, you could do the following in your mongodb.ts file:

import mongoose from 'mongoose';

const { MONGO_URI } = process.env;

if (!MONGO_URI) throw new Error('MONGO_URI is not defined.');

let cached = global.mongoose;

if (!cached) cached = global.mongoose = { conn: null };


export const connectMongo = async () => {

  if (cached.conn) return cached.conn;

  cached.conn = await mongoose.connect(MONGO_URI);
  
  return cached.conn;
};

Then when you declae your type you wouldn't need the promise:

import { Mongoose } from 'mongoose';

/* eslint-disable no-var */

declare global {
  var mongoose: {
    conn: Mongoose | null;
  };
}

Is there any reason you could not do this?

@Jared-Dahlke
Copy link

i'm not getting typesafety / flowthrough from this

@kaiiak
Copy link

kaiiak commented Apr 13, 2023

Great! Solve "OverwriteModelError" error in next.js with typescript~

@moaaz-bhnas
Copy link

Thank you so much for this!

@magicdev122
Copy link

Thank you for your effort

@Hassan-Dawood
Copy link

thanks

@yeasin2002
Copy link

Thanks, It did worked for my project

@Velunce
Copy link

Velunce commented Nov 7, 2024

Thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment