1
votes

I'm learning TypeScript and playing around with mongoose. I have the following Schema definition (simplified form):

interface IContact extends Document {
  type: string;
  firstName?: string;
}

const contactSchema = new mongoose.Schema({
  contactType: {
    type: String,
    required: true,
    trim: true,
    enum: ['person', 'general']
  },
  firstName: {
    type: String,
    required: function() {
      return this.contactType === 'person';
    },
    minlength: 1,
    trim: true
  }})

 const Contact = mongoose.model<IContact>('Contact', contactSchema);

Now, the TypeScript compiler gives me the following error:

Property 'contactType' does not exist on type 'Schema | SchemaType | SchemaTypeOpts'. Property 'contactType' does not exist on type 'Schema'.

Is validating a required field this way, taken from the mongoose documentation, correct (using the this keyword), or is there another way? Or, should I annotate my Schema in a way, that TypeScript will know that the contactType property exists on my Schema?

1

1 Answers

0
votes

You can try this, this worked for me:

// ...contactSchema declaration above... //

contactSchema.obj.firstName.required = function() {
  return this.contactType === 'person';
};

// ...Contact model declaration below... //