CampbellSoftwareSolutions / mongoose-id-validator

Mongoose plug in to validate ObjectID references point to valid existing documents.
Other
47 stars 26 forks source link

Not working with array schemas in mongoose@5.4.0+ #35

Closed makinde closed 4 years ago

makinde commented 4 years ago

My schema definition looks like this:

const groupSchema = new mongoose.Schema({
  name: {
    type: String,
    trim: true,
  },
  members: {
    type: [String],
    ref: 'Profile',
    refConditions: inSameOrgRefCondition,
    set: idListSetter,
  },
});

This results in a schemaType that looks like this in mongoose@5.4.0.

SchemaArray {
  casterConstructor:
   { [Function: SchemaString]
     schemaName: 'String',
     _cast: [Function: castString],
     cast: [Function: cast],
     get: [Function],
     _checkRequired: [Function],
     checkRequired: [Function] },
  caster:
   SchemaString {
     enumValues: [],
     regExp: null,
     path: 'members',
     instance: 'String',
     validators: [],
     getters: [],
     setters: [],
     options: {},
     _index: null },
  '$isMongooseArray': true,
  path: 'members',
  instance: 'Array',
  validators: [],
  getters: [],
  setters: [ [Function: idListSetter], [Function: membersSetter] ],
  options:
   { type: [ [Function: String] ],
     ref: 'Profile',
     refConditions: { org: [Function: orgFromDocument] },
     set: [Function: idListSetter] },
  _index: null,
  defaultValue: { [Function: defaultFn] '$runBeforeSetters': true },
  isRequired: true,
  requiredValidator: [Function],
  originalRequiredValue: true }

The following code doesn't recognize the members field as an array:

        if (schemaType.options && schemaType.options.ref) {
            validateFunction = validateId
            refModelName = schemaType.options.ref
            if (schemaType.options.refConditions) {
                conditions = schemaType.options.refConditions
            }
        } else if (schemaType.caster && schemaType.caster.instance &&
            schemaType.caster.options && schemaType.caster.options.ref) {
            validateFunction = validateIdArray
            refModelName = schemaType.caster.options.ref
            if (schemaType.caster.options.refConditions) {
                conditions = schemaType.caster.options.refConditions
            }
        }
martin-css commented 4 years ago

Published in v0.5.4