📅  最后修改于: 2023-12-03 15:18:11.085000             🧑  作者: Mango
这是一个错误提示,意味着在编译后,试图覆盖一个已经存在的模型,出现了失败的情况。
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);
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);
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;
const { Users } = require('./model');
// 'Users' model already defined in model.js, won't throw OverwriteModelError
const UsersStore = mongoose.model('UsersStore', userSchema);