Sunday, 7 May 2017

nodejs express response append into a list

I have multiple res.send in one route, how can I append them all into one and send the accumulated list at the end? I prefer to do it in the following form:

{
"writer": {success message},
"archive": {success message},
 ...
}

and another one like above for the list errors. here is the code:

router.post('/some/route', function (req, res) {
    if (req.isLoggedIn()) {
        return res.status(403).json({});
    }
    MyModel.findById(req.user._id,function (err, data) {
        if(err || data.rights !== 'super'){
            return res.status(403).json({});
        }
        if(req.body.writer){
            Books.update(
                { writer : req.body.id},
                { $set : { writer : req.body.writer} },
                function (err) {
                    if(err){
                        res.status(500).send(err);
                    }
                    else{
                        res.status(200).send('updated successfully.');
                    }
                }
            );
        }else{
            Books.remove({writer: req.body.id}, function(err){
                if (err){ return console.log(err)}
            });
        }

        MetaInfo.findOneAndRemove({_id: req.body.id}, function (err, data) {
            console.log(err);            
        });
        Archive.findOne({_id: req.body.id},function (err, data) {

            smtpTransporter.sendMail({...}, function (error, response) {
                if (error) {
                    console.log(error);
                } else {
                    console.log("Mail sent");
                }
                smtpTransporter.close();
            });

            data.remove();
            if (err) {
                console.log(err);
                return res.status(200).json({
                    success: false,
                    message: 'server error',
                    err: err
                });
            }
            res.status(200).json({
                success: true
            });
        })
    });
});



via cplus

No comments:

Post a Comment