如何在Mongoose Schema中引用同键并同步对应值
实现Mongoose字段复用与自动同步的方案
1. 复用字段定义
先把顶层name和age的Schema配置抽成独立变量,这样数组内的子文档能直接引用,避免重复编写相同的验证规则与类型定义:
const mongoose = require('mongoose') // 抽离可复用的字段配置 const nameField = { type: String, required: true } const ageField = { type: Number } const _Schema = new mongoose.Schema({ name: nameField, age: ageField, key_example: [{ name: nameField, age: ageField }] })
2. 用预保存中间件自动同步值
要实现创建文档时自动将顶层name和age同步到key_example数组,使用Mongoose的pre('save')中间件,在文档保存前完成赋值:
// 添加预保存钩子 _Schema.pre('save', function(next) { // 仅在新文档创建且key_example为空时初始化 if (this.isNew && (!this.key_example || this.key_example.length === 0)) { this.key_example = [{ name: this.name, age: this.age }] } next() }) const model = mongoose.model("person", _Schema) async function CreateAndSave () { const _Person = new model({name:"mohe", age:33}) await _Person.save() } CreateAndSave()
可选:更新顶层字段时同步更新数组值
如果需要在更新顶层name/age时同步更新key_example内的对应值,可以添加pre('findOneAndUpdate')中间件:
_Schema.pre('findOneAndUpdate', function(next) { const updateData = this.getUpdate() // 检测是否更新了name或age字段 if (updateData.name || updateData.age) { this.setUpdate({ ...updateData, $set: { 'key_example.0.name': updateData.name || this._conditions.name, 'key_example.0.age': updateData.age || this._conditions.age } }) } next() })
内容的提问来源于stack exchange,提问作者Mustafa
相关产品推荐
相关产品推荐

