简体   繁体   中英

How can i validate the data before inserting into table?

function bulkinsertion(req,res){

var i;
var student = req.body;
var successCount=0 , errorCount=0;

for(i=0;i<student.length;i++){
    models.Student.create(student[i]).then(result =>{
      successCount++;
     }).catch(error =>{
        errorCount++;
     });
} 
res.status(200).json({
    message:"success",
    successCount:successCount
})

console.log(successCount,errorCount);

}

I have 3 columns in my table namely Name, Sem, Branch so how can i validate these 3 columns before inserting into the table?

You can add validations inside the for loop somewhat similar to code below as per your requirements

function bulkinsertion(req,res){

var i;
var student = req.body;
var successCount=0 , errorCount=0;

for(i=0;i<student.length;i++){
  if(student.Name && student.Name.length > 5 && student.Sem && student.Branch && student.Branch.length > 3) {
    models.Student.create(student[i]).then(result =>{
      successCount++;
     }).catch(error =>{
        errorCount++;
     });
  }
} 
res.status(200).json({
    message:"success",
    successCount:successCount
})

console.log(successCount,errorCount);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM