0

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.

2 Answers 2

1

The issue is that database.sequelize.sync().then() is asynchronous and by the time each runs, the loop counter has iterated to the last value.

Try this

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]
        }));
}
Sign up to request clarification or add additional context in comments.

3 Comments

The first way causes the number "2" to be stored in each row for my interest column. The second way causes no information to be stored in the interest column of the table, just the userId is stored in three separate rows, but no interest value :(
@JaredHart I updated the answer. please try the new solution
Hi Kane, I arrived at the same solution at the same time! It works now! Thanks so much for the help, really appreciate it.
0

So I was able to figure out a solution, however I'm worried that it might be inefficient. Could someone please take a look?

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]
        }));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.