node.js用于用户数据输入和数据更新的验证和错误处理

时间:2016-06-22 17:06:15

标签: javascript node.js validation express mongoose

heloo,我有一个正在构建的API,我需要适当的验证来处理用户输入,如果用户输入一个空字段,或者如果用户想要编辑他需要输入的数据并且ID是验证器应检查,如果输入未定义或为null,则应处理。

router.post('/update',function(req,res){

var language = req.body.language,
    country_id = req.body.country_id,
    city_id = req.body.city_id,
    pickup_points = req.body.pickup_points,
    static_address = req.body.static_address,
    address_id= req.body.address_id;

// if(address_id == null || address_id == undefined ){
//  res.json({success: false, message : "address wasn't updated"});

// }else{

    Address.findById(address_id,function(err,address){
    if(err) {res.json({success:false , message:"please enter a valid address Id"});
    }
    });
    req.assert('address_id', 'Invalid address id').notEmpty();
     var errors = req.validationErrors();
     if (errors) {
     res.json({success:false,message:"please enter address ID " });

     }

    Address.findById(address_id,function(err,address){
        address.language = req.body.language != null && req.body.language !=undefined ? req.body.language : address.language;
        address.country_id = req.body.country_id != null && req.body.country_id !=undefined ? req.body.country_id : address.country_id;
        address.city_id = req.body.city_id != null && req.body.city_id !=undefined ? req.body.city_id : address.city_id;
        address.pickup_points = req.body.pickup_points != null && req.body.pickup_points !=undefined ? address.pickup_points.push(req.body.pickup_points) : address.pickup_points;
        address.static_address = req.body.static_address != null && req.body.static_address !=undefined ? req.body.static_address : address.static_address;

        address.save(function(err,student){
            if(err){
                console.log(err);
            }else{

            res.json({success : true , message : "address successfully updated"  });}
        });
    });
// }

这是一个代码示例,以及我如何处理验证,但如果在数据库中找不到ID则代码崩溃

0 个答案:

没有答案