0

I have a schema in which a field is marked as required,I have many records to insert to db but one record will not have the field which is marked as required, but I would like to insert that record also without entering data to the filed that is marked as required. Is there any posiibilty that I can do insertion to db in such a way. How can I manage that record from giving the error field required.

fi

e
ld2: {
          type: String,
          required: function() {
            if(this.field2) { return true }
            else return false
          }
        }
        //trying to insert the data from controller
        //some code..
        let jsonData ={field2 :"",field2 :'abcd'}
        var test = new SchemaTest()//creating schema instance
        for(var i in jsonData)
        //for below code for first iteration field2  have no data, 
        //second have data
        test.field2 = jsonData.field2 
        test.save((err,test)=> {})
learnNcode
  • 149
  • 2
  • 4
  • 16

1 Answers1

0

The probable thing to do would be to remove the required field. If not all records will have the field filled then it should not be set as required. You can otherwise use an if statement to set it to true if some other property turns to be true.

//Other code.
field1 :{
  type: Boolean,
  required: true
},
field2: {
  type: String,
  required: function() {
    if(this.field1) { return true }
    else return false
  }
}
// Rest of code
BrianDev
  • 476
  • 5
  • 10