📜  OverwriteModelError:编译后无法覆盖“UsersStore”模型. (1)

📅  最后修改于: 2023-12-03 15:18:11.085000             🧑  作者: Mango

OverwriteModelError: Failed to overwrite 'UsersStore' model after compilation.

简介

这是一个错误提示,意味着在编译后,试图覆盖一个已经存在的模型,出现了失败的情况。

常见原因
  • 在执行 mongoose.model() 时,试图创建之前已经定义过的模型。
  • 在多个文件中引用同一个模型,但是在其中的一个文件中对该模型进行了重复定义。
解决方案
  • 确认代码中是否确实存在重复定义模型的行为,及时删除。
  • mongoose.model() 中使用 exists() 方法来检查模型是否已经存在,如果存在则不进行重新定义。
  • 将模型定义集中在一个文件中,并将其导出,其他文件中引用该模型。
示例代码
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
  password: { type: String, required: true }
});

// 'Users' model already defined
mongoose.model('Users', userSchema);

// 'UsersStore' has a typo
const userStore = mongoose.model('UsersStroe', userSchema);

// Attempting to overwrite existing 'Users' model, throwing OverwriteModelError
const Users = mongoose.model('Users', userSchema);
解决方案一:删除重复定义的模型
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
  password: { type: String, required: true }
});

// 'Users' model already defined
mongoose.model('Users', userSchema);

// 'UsersStore' has a typo
const userStore = mongoose.model('UsersStroe', userSchema);

解决方案二:使用 exists() 方法检查模型存在与否
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
  password: { type: String, required: true }
});

// 'Users' model already defined
mongoose.model('Users', userSchema);

// Check if 'UsersStore' model already exists before defining it
if (!mongoose.models['UsersStore']) {
  const userStore = mongoose.model('UsersStore', userSchema);
}

// Though the 'Users' model is being defined again, it won't throw OverwriteModelError
const Users = mongoose.model('Users', userSchema);

解决方案三:将模型定义集中在一个文件中
model.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
  password: { type: String, required: true }
});

const Users = mongoose.model('Users', userSchema);

module.exports.Users = Users;
index.js
const { Users } = require('./model');

// 'Users' model already defined in model.js, won't throw OverwriteModelError
const UsersStore = mongoose.model('UsersStore', userSchema);