mongodb 覆盖模型错误:在Mongoose.model中,编译后不能覆盖'User'模型

k97glaaz  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(124)

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 });
      }
}

`

qyzbxkaa

qyzbxkaa1#

在导出模型之前,请尝试检查是否已声明模型:

const User = mongoose.models.User || mongoose.model('User', UserSchema);

export default User;

相关问题