2
votes

I'm trying to define a mongoose schema where I have a mixed type but want to make some properties required while still allowing anything there. Is this event possible?

new Schema({
  myProperty: {
    name: {
      type: String,
      required: true,
    }
    <anything else>    
  }
})

Only pseudo solution I found was to define property level where I can have a mixed type, but I would like to avoid it:

new Schema({
  myProperty: {
    name: {
      type: String,
      required: true,
    }
    additionalData: Object,    
  }
})
1

1 Answers

0
votes

You can use a validator for a mixed :

Your schema will be :

const UserSchema = new Schema({
  myProperty: {
    type: mongoose.Schema.Types.Mixed    
  }
})

And your validator :

UserSchema.path('myProperty').validate(function (value) {
  return value && value.name !== undefined && typeof value.name === "string";
}, 'name is a required string');

Then if you try it with :

const User = mongoose.model('User', UserSchema);

let u = new User({ myProperty: {name: "bar" }})
console.log(u.validateSync())
// undefined => validation passed

u = new User({ myProperty: {foo: "bar" }})
console.log(u.validateSync())
// { ValidationError: User validation failed: myProperty: name is a required string