I am creating a mongoose model called User. Then when I import the model on the two different controllers the mongoose show me the error 'OverwriteModelError: Cannot overwrite User
model once compiled. at Mongoose.model' Please help me if there is any one who face this error before.
My User Model User.js
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
min: 2,
max: 100,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 5,
},
city: String,
state: String,
country: String,
occupation: String,
phoneNumber: String,
transactions: Array,
role: {
type: String,
enum: ["user", "admin", "superadmin"],
default: "admin",
},
},
{ timestamps: true }
);
const User = mongoose.model('User', UserSchema) ;
export default User;
The controllers Client.js
import User from "../models/User.js";
export const getCustomers = async (req, res) => {
try {
const customers = await User.find({ role: "user" }).select("-password");
res.status(200).json(customers);
} catch (error) {
res.status(404).json({ message: error.message });
}
};
General.js
import User from '../models/user.js'
export const getUser = async (req, res) => {
try {
const { id } = req.params;
const user = await User.findById(id);
res.status(200).json(user);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
`
1条答案
按热度按时间qyzbxkaa1#
在导出模型之前,请尝试检查是否已声明模型: