2017-05-23 58 views
0

我的應用程序首次創建帳戶時發送包含用戶信息的正文消息。其中一個值是「Interests」數組,我的目標是讓我的Node.js Web服務將「Interests」數組的每個值作爲一個單獨的行存儲在我的一個mysql數據庫表中。但是,問題是我的「興趣」數組的最後一個值是針對每一行存儲的。下面,你會發現更多細節無法將數組的每個值作爲單獨的行存儲在數據庫表中

req.body例如:

{"firstName": "Mason", 
"lastName": "Rad", 
"age": 19, 
"userId": "radMas28", 
"userPassword": "fgjfh4534534", 
"interests": ["hockey", "baseball", "basketball"] 
} 

我已經試過:

var storeInterests = function(body) { 
    for(var interest in body.interests) { 
     database.sequelize.sync() 
      .then(() => database.Interests.create({ 
       userId: body.userId, 
       interest: body.interests[interest] 
      })); 
    } 
}; 

會存儲在我的數據庫:

enter image description here

我也試過使用while循環,直到計數器值爲止riable到達body.interests數組.length屬性,但是發生了同樣的問題。

非常感謝您的幫助。

回答

1

問題是,database.sequelize.sync()。then()是異步的,每次運行時,循環計數器都迭代到最後一個值。

試試這個

var storeInterests = function(body) { 
    for(var i=0; i<body.interests.length; i++) { 
    store(body.userId, body.interests[i]) 
    } 
}; 

function store(userId, interest) { 
    database.sequelize.sync() 
     .then(() => database.Interests.create({ 
      userId: userId, 
      interest: body.interests[i] 
     })); 
} 
+0

第一種方法導致數字「2」存儲在我的興趣列的每一行中。第二種方法導致沒有信息存儲在表的興趣列中,只是userId存儲在三個單獨的行中,但沒有興趣值:( –

+1

@JaredHart我更新了答案,請嘗試新的解決方案 – kane

+1

Hi Kane,我同時到達相同的解決方案!它現在可行!非常感謝您的幫助,非常感謝。 –

0

所以我能夠找出一個解決方案,但是我很擔心,這可能是低效的。有人可以看看嗎?

var storeInterests = function(body) { 
    for(var counter in body.interests) { 
     interestFunction(body.userId, body.interests, counter); 
    } 
}; 

var interestFunction = function(id, interests, counter) { 
    database.sequelize.sync() 
     .then(() => database.Interests.create({ 
      userId: id, 
      interest: interests[counter] 
     })); 
} 
相關問題