NodeJS - 根据请求更新对象

时间:2017-03-14 12:41:14

标签: javascript node.js

我有以下对象:

 var user = {

        firstName: req.body.first_name,
        lastName:  req.body.last_name,
        email:     req.body.email,
        password: "",
        id:         "", 
    };

现在我要做的是向API发布请求,如果用户成功保存在数据库中,它将返回用户ID和密码(然后可以通过电子邮件发送给该人) ..

request.post({

       url: process.env.API_SIGNEDIN_ENDPOINT + "users/store",
       form: user,
       headers: {
         Authorization: "Bearer " + req.session.authorization
       }

    }, function(error, response, body) {

       // Check the response
       var theResponse = JSON.parse(response.body);

       if(theResponse.code == 400)
       {
          var error = [
            {param: "email", msg: "This email address has already been taken!", value: ""}
          ];

          res.render("create", {
              errors: error,
          });
       }else{

         var theUser = JSON.parse(body);
         user.password = theUser.password;
         user.id       = theUser.id;
       }
    });

这很好,但是,每当我尝试输出user时,它都不会更新此帖子之外的user对象。用户对象很好,它正在工作,问题似乎是从我尝试从此结果回调访问用户时。有什么想法吗?

编辑:

假设我有“地址1”(这是人员主要地址),我有“地址2”(这是人员的第二地址)..此人可能只有1个地址,因此我只需要保存一个地址。但是,使用将所有内容放在.then()中的逻辑意味着我无法执行此操作,因为用户可能没有2个地址但我仍需要访问主地址,例如:

mainAddress.save().then(function(addressData) {

              var theAddressLicenceTick = req.body.address_licence;

              if(theAddressLicenceTick)
              { 
                  var subAddress = models.addresses.build({ 
                      address_1:    "asasfasf", 
                      city:         "asfafsaf", 
                      postcode:     "asfasf", 
                      created_at:   new Date(), 
                      updated_at:   new Date(); 
                  }); 

                  subAddress.save().then(function(subAddress) {

                      // continue integration 
                      // would I have to do the functionality again?

                  }); 

              }else{
                  // The user only has one address 

              }
         });

基本上,我有一个customer表,通过链接表可以有多个addresses。但我相信有一种更简单的方法,而不是编写所有这些代码?

0 个答案:

没有答案