Adding a validator to an existing schema with mongoose

I have a mongoose schema that looks like this:

const userSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true,
        minlength: 4,
        maxlength: 20,
        validate: {
            validator: username => !username.startsWith('banned_prefix')
            msg: 'This username is invalid',
            type: 'username-validation-1'
        }
    }
});

I want the schema to look like this:

const userSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true,
        minlength: 4,
        maxlength: 20,
        validate: [
            {
                validator: username => !username.startsWith('banned_prefix')
                msg: 'This username is invalid',
                type: 'username-validation-1'
            },
            {
                validator: username => !username.startsWith('new_banned_prefix')
                msg: 'This username is invalid',
                type: 'username-validation-2'
            }
        ]
    }
});

How do I do this given that the database and schema already exist and I don't want to completely delete and reset the db?

I tried writing a migration using the native mongodb node driver based on https://docs.mongodb.com/manual/core/schema-validation/#existing-documents. However, it seems like mongoose doesn't actually add native mongodb validators for the validators specified in the schema. That is, when I printed out the validator data for the collection, I get an empty object:

// prints {}
console.log((await db.listCollections({ name: 'users' }).toArray())[0].options.validator);

I don't want to add this new validator in a way that makes it different from the existing validators I have on the schema.

Answers 1

  • Actually, it looks like this isn't an issue at all because, I presume, mongoose isn't using mongodb native validators so there doesn't need to be any change to the actual db. Mongoose will pick up a validator change like this automatically, no migration necessary.

    This wasn't clear to me at first because I was trying to manually recreate the model with the mongoose.model function and was getting errors about overwriting an existing model.


Related Articles