Search code examples
node.jsmongodbexpressvalidationmongoose

Validator function is not working in mongoose


I want to check if my document to have a media URL so it should have a media type too i added this validator

mediaURL: {
                type: String,
                default: ''
            },
            mediaType: {
                type: String,
                enum: ['video', 'photo', 'audio', 'none'],
                validate: {
                  validator: function () {
                    return( (this.mediaURL && this.mediaType) || !this.mediaURL );
                  },
                  message: 'There should be a mediaURL in the post to have a media type',
                }
              },

i am using mongoose and it is not working i still can save the document without a media type while having a media url.

i have tried different way to implement the validation like this way

mediaType: {
    type: String,
    enum: ['video', 'photo', 'audio', 'none'],
    validate: {
        validator: function () {
            if (!this.mediaURL) {
                // No mediaURL, so mediaType is allowed to be empty
                return true;
            }
            return !!this.mediaType; // Ensure mediaType is present when mediaURL is provided
        },
        message: 'There should be a mediaURL in the post to have a media type',
    }
},

but it still is not working


Solution

  • You can do something like:

    Schema.pre('validate', function (next) {
      if (this.mediaURL && !this.mediaType) { 
        this.invalidate('mediaType', 'mediaType cannot be empty', this.mediaType);
      }
    
      next();
    });
    
    1. Schema.pre defines a pre-hook for the schema. This is a middleware (and not a validator function), and as such doesn't matter whether you return true or false.

    Once your middleware code is executed, you need to call next() to continue execution.

    https://mongoosejs.com/docs/api/schema.html#Schema.prototype.pre()

    1. invalidate() marks a path in your schema as invalid, which will cause the validation to fail.

    This is where your custom validation happens (by checking for mediaURL and mediaType).

    https://mongoosejs.com/docs/api/document.html#Document.prototype.invalidate()