CampbellSoftwareSolutions / mongoose-id-validator

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

Undefined model when using refPath #43

Open crashmark opened 2 years ago

crashmark commented 2 years ago

The error occurs when I use refPath for dynamic referencing with nested elements, when I add a new record.

Model

const userSchema = new Schema({
  ...
  activeServices: [{
    service: {
      type: Schema.Types.ObjectId,
      required: true,
      refPath: 'activeServices.serviceType'
    },
    serviceType: {
      type: 'String',
      required: true,
      enum: ['Model1', 'Model2', 'Model3']
    }
  }]
})

Controller

User.findById(id)
  ...
  .then(user => {
    user.set({activeServices: [...user.activeServices, {serviceType: service.serviceType, service: mongoose.Types.ObjectId(service.serviceId)}]})
    user.save()
  })

ERROR

ERROR - service:express:  Error: User validation failed: activeServices.0.serviceId: Schema hasn't been registered for model "undefined".Use mongoose.model(name, schema)

PATCH

// lib/id-validator.js
...
const refModelPathSplits = refModelPath.split('.')
if(refModelPathSplits.length > 1) localRefModelName = this[refModelPathSplits[refModelPathSplits.length-1]]
else localRefModelName = this[refModelPath]
...

versions: