V
V
Valery Orlov2018-10-23 15:55:39
JavaScript
Valery Orlov, 2018-10-23 15:55:39

How to correct the code?

The code below checks. whether the device collection has a mobile device with the id aid. If so, it updates the localTime, battery fields, returning a response. that the operation worked correctly. If the device is not found, it is added with all fields, provided that the user collection contains the email address req.body.email.

Device.find({ aid: req.body.aid })
        .select()
        .exec()
        .then(dev => {
          if (dev.length >= 1) {              
              console.log('Обновляем устройство.');
              const UpdateDevice = new Device({
              localTime: req.body.localTime, 
              battery: req.body.battery
            });
            Device.update({ aid: req.body.aid }, { $set: UpdateDevice })
              .exec()
              .then(result => {
                if(result){                   
                 res.status(200).json({
                   "id": dev[0]._id,
                   "result":"ok",
                  });
                 }
               })
          } else {
            console.log('Добавляем новое устройство.');
             const NewDevice = new Device({
               _id: new mongoose.Types.ObjectId(),
               localTime: req.body.localTime, 
               setupNumber: req.body.setupNumber, 
               email: req.body.email,
               aid: req.body.aid
            });   
       NewDevice.save().then(result => {
            if(result) {
            mailer(`В ваш аккаунт успешно добавлено новое устройство`);
            User.find({ 'local.email': req.body.email })
            .select()
            .exec()
            .then(user => {
              res.status(200).json({
                "id": NewDevice['_id'],
                "result":"ok",
               });   
             }); 
            } else  {   
                      res.status(500).json({
                       Error: "Ошибка добавления мобильного устройства в б.д..."   
                      }); 
            }   
            }).catch(err => {
              console.log(err);
                res.status(500).json({
                 error: err
                });
               });
              }   
            });

The code seems pretty junk. How would you optimize and simplify it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question