5月29日 01:07

Mongoose Schema 怎么定义,有哪些常用配置项?

Schema 是 Mongoose 的文档结构蓝图,定义字段类型、验证规则、默认值和索引。它本身不操作数据库,需通过 mongoose.model() 编译为 Model 后使用。核心配置项包括:类型声明(String/Number/Date/ObjectId/Array)、验证器(required/min/max/enum/match)、修饰符(trim/lowercase/uppercase)、默认值(default)和索引(unique/index/sparse)。

追问

Schema 的 strict 选项有什么作用? strict 默认为 true,未在 Schema 中声明的字段会被自动忽略,不会写入数据库。设为 false 允许存储任意字段,但不推荐,会丧失结构约束的意义。

虚拟字段怎么定义,和普通字段有什么区别? 通过 schema.virtual('name').get() 定义,不存入数据库、不占存储、不能用于查询筛选。适合拼接展示字段(如 fullName),不适合业务排序或过滤。

Schema 怎么添加实例方法和静态方法? 实例方法用 schema.methods.xxx = function(),通过文档实例调用,this 指向文档;静态方法用 schema.statics.xxx = function(),通过 Model 类调用,this 指向 Model。注意不要用箭头函数,否则 this 绑定错误。

嵌套文档和引用(ref)该选哪个? 嵌套文档适合一对一或少量子文档,查询简单但文档体积大;引用(ref + ObjectId)适合多对多或大数据集,需 populate 联查但文档精简。频繁一起读取用嵌套,独立生命周期用引用。

写段代码

js
const postSchema = new mongoose.Schema({ title: { type: String, required: true, trim: true }, author: { type: Schema.Types.ObjectId, ref: 'User', required: true }, tags: [{ type: String, enum: ['js', 'node', 'db'] }], views: { type: Number, default: 0, min: 0 } }, { timestamps: true });
标签:Mongoose