I was working on using Next auth with credentials, but I keep encountering TypeError: Cannot read properties of undefined (reading 'User') problem whenever I import the UserModel. Here is my auth/[...nextauth]/route.js code
// authOptions.js
import NextAuth from "next-auth/next";import CredentialsProvider from "next-auth/providers/credentials";import bcrypt from "bcryptjs";import connectToDB from "@/lib/database";import { compare } from "bcryptjs";import User from "@/models/user";export const authOptions = { providers: [ CredentialsProvider({ name: "credentials", credentials: { userName: { label: "Username", type: "text" }, password: { label: "Password", type: "password" }, }, async authorize(credentials) { const { userName, password } = credentials; console.log("Authorize: Received credentials:", credentials); try { // Establish database connection await connectToDB(); // Query User model using the database connection const user = User.findOne({ userName }); console.log("Authorize: Found user:", user); if (!user) { console.log("Authorize: User not found"); return null; } const passwordsMatch = await bcrypt.compare(password, user.password); if (!passwordsMatch) { console.log("Authorize: Passwords don't match"); return null; } console.log("Authorize: Authentication successful"); return { id: user._id, name: user.name, email: user.email }; } catch (error) { console.error("Error during authorization: ", error); return null; // Explicitly return null in case of an error } },}), ],session: { strategy: "jwt", },secret: process.env.NEXTAUTH_SECRET,pages: { signIn: "/login",},}; const handler = NextAuth(authOptions);export { handler as GET, handler as POST };
`
Here is the code for the user schema
import { Schema, model, models } from "mongoose";const UserSchema = new Schema( { name: { type: String, required: true, }, userName: { type: String, required: true, unique: true,},email: { type: String, required: true, unique: true,},image: String,color: String,password: { type: String, required: true,},departmentID: { type: Schema.Types.ObjectId, ref: "Department", required: true,},role: { type: String, enum: ["admin", "teacher", "student", "admin-teacher"], required: true,},sex: { type: String, enum: ["female", "male"], required: true,},status: { type: String, enum: ["active", "deprecated", "inactive"], default: "active",},
},{timestamps: true,}
);
const User = models.User || model("User", UserSchema);export default User;
What exactly is the problem here?
I tried console logging the errors and checked Model Export/Import and checked the database connection as well