Skip to content

Undefined model when using refPath#43

Open
crashmark wants to merge 1 commit intoCampbellSoftwareSolutions:masterfrom
crashmark:master
Open

Undefined model when using refPath#43
crashmark wants to merge 1 commit intoCampbellSoftwareSolutions:masterfrom
crashmark:master

Conversation

@crashmark
Copy link
Copy Markdown

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:

  • node: "v14.19.0"
  • mongoose: "^5.13.14"
  • mongo: "5.0.6"
  • express: "^4.17.1"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants