解决Mongoose Cannot overwrite model once compiled

在开发中使用mongoosejs,你可能遇到模型在不同文件中引用时,会发生以下错误,那是因为mongoosejs重新创建一次而导致的Mongoose OverwriteModelError: Cannot overwrite model once compiled

1 min read
By myfreax
解决Mongoose Cannot overwrite model once compiled

在开发中使用mongoosejs,你可能遇到模型在不同文件中引用时,会发生以下错误,那是因为mongoosejs重新创建一次而导致的

Mongoose OverwriteModelError: Cannot overwrite model once compiled

首先我们看看mongoose文档的示例,像这种方式定义的都是不能在多个文件中引用的

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true});

const Cat = mongoose.model('Cat', { name: String });

const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));

如果你想在多个文件引用model文件,可以使用下面方式创建model型,这样可以解决上面的Mongoose OverwriteModelError: Cannot overwrite model once compiled错误

const mongoose = require('mongoose');
const { Schema } = mongoose;
const ObjectId = mongoose.Schema.Types.ObjectId;


module.exports = mongoose.createModel('tag', new Schema({
    name: String,
    visits: { type: Number, default: 0 },
    slug: String,
    title: String,
    description: String,
    feature_image: String,
    feature_width: Number,
    feature_height: Number,
    parent_id: ObjectId,
    level: Number,
    create_at: { type: Date, default: Date.now },
    update_at: { type: Date, default: Date.now }
}))