简体   繁体   中英

Mongoose child schema validation against properties of parent

I would like to implement some validation logic within a child document, that validation is related to the state of a field of its parent. My code looks like:

const childSchema = function (parent) {

  return new Schema({
    name: {
      type: String,
      set: function (v) {
        const prefix = (parent.isFlashed) ? 'with' : 'without'
        return `${prefix} ${v}`
      }
    },
    version: String
  })
}

const parentSchema = new Schema({
  isFlashed: Boolean,
  firmware: childSchema(this)
})

I'm wondering why my code doesn't work and how can I check the value of a property of the parent schema inside my child schema.

Thanks in advance

You don't need to define your child schema as a function that returns a new Schema . You just reference the child schema in the parent.

const ChildSchema = new Schema({
    name: {
        type: String,
        set: function(v) {
            const prefix = this.parent().isFlashed ? 'with' : 'without';
            return `${prefix} ${v}`;
        }
    }
});

const ParentSchema = new Schema({
    isFlashed: Boolean,
    firmware: ChildSchema
});

You'll notice that I reference the parent object as a function of this : this.parent() .

When you're creating a new parent object with a child, you just use a nested object that matches the format of the child schema.

const Parent = mongoose.model('Parent', ParentSchema);
const parent = new Parent({isFlashed: false, firmware: {name: "ChildName"}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM