0

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 Answers2

0

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.

J.F.
  • 13,927
  • 9
  • 27
  • 65
  • I dont want **promises** in the schema when **isVoter** is **true**. Your solution allows to add **promises** even if **isVoter** is **true**. – Puneet verma Feb 06 '21 at 16:34
  • Set false insetad of true. Anyway, if it is not the desired behaviour try to explain better the problem. – J.F. Feb 06 '21 at 16:35
  • actually I want that if a person is voter, which means **isVoter == true**, then he/she will not have made any promises that means no one **should be able to add promises** when he/she is a voter. But your solution suggests that inspite of **isVoter == true**, promises can still be added. – Puneet verma Feb 06 '21 at 16:42
0

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

Mohammad Yaser Ahmadi
  • 4,664
  • 3
  • 17
  • 39