无法将数组的每个值存储为数据库表中的单独行

时间:2017-05-23 21:19:56

标签: mysql node.js sequelize.js

我的应用在首次创建帐户时会发送包含用户信息的正文消息。其中一个值是"兴趣"数组,我的目标是让我的Node.js网络服务存储"兴趣"数组作为我的一个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循环,直到计数器变量到达body.interests数组.length属性,但是同样的问题也出现了。

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

问题是database.sequelize.sync()。then()是异步的,每次运行时,循环计数器都迭代到最后一个值。

试试这个

Files | Recent Files

答案 1 :(得分: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]
        }));
}