Tuesday 23 May 2017

Unable to store each value of array as separate rows in database table

My app sends off a body message with a user's information when they first create an account. One of the values is an "Interests" array, and my goal is to have my Node.js web service store each value of the "Interests" array as a separate row in one of my mysql database tables. However, the issue is that the last value of my "Interests" array is stored for each row. Below, you will find further details

req.body example:

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

What I've tried:

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

What's stored in my database:

enter image description here

I've also tried using a while loop that continues until the counter variable reaches the body.interests array .length property, however the same issue occurred.

Your help is very much appreciated.



via Jared Hart

No comments:

Post a Comment