How to make mongoose schema dynamic, depending upon the value?

786 views Asked by At

I am new to mongoose and I have searched alot about it and was not able to find out the ans. Please help, thanks in advance.

const user = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    rollno: {
        type: Number,
        required: true,
        unique: true,
        
    },
    password : {
        type: String,
        required: true,
    },
    isVoter: {
        type: Boolean,
        required: true,
        default: true
    }
}, {
    timestamps: true
});

Can I have a schema which would be dependent on the value of isVoter. For example if value of isVoter is false then we should have schema like this :

const user = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    rollno: {
        type: Number,
        required: true,
        unique: true,

    },
    password : {
        type: String,
        required: true,
    },
    isVoter: {
        type: Boolean,
        required: true,
        default: true
    },
    promises: [
        {
           type: String
        }
    ]
    , {
    timestamps: true
});
2

There are 2 answers

0
Mohammad Yaser Ahmadi On

you can use pre hook in mongoose, check the documentation and before saving, check the isVoter value, if you don't want to save promises, try this.promises = undefined

user.pre('save',  function(next) {
    if(this.isVoter== true){
       this.promises = undefined
    }
    else{
      this.promises = "hello"
      //do somethings
    }
   next();
});

and in the schema promises should be definded

3
J.F. On

You can defined if one variable is required or not based in another property in this way:

promises: [
        {
           type: String,
           required: function(){
             return this.isVoter == false
           }
        }
    ]

So, promises will be required only if isVoter is false. Otherwise will not be required.