gpt4 book ai didi

javascript - 如何使用node js将对象数组插入到mysql中?

转载 作者:行者123 更新时间:2023-11-29 10:53:44 26 4
gpt4 key购买 nike

我是 Node js 新手。我很困惑如何使用 NodeJS 将对象数组插入到 mysql

我的代码

static inserPost(postCardArray,postTitle,postedDate,username,coords){
//postCardArray = [ {hello:'dude'} ]
let query = "INSERT INTO ??(??,??,??,??,??,??) VALUES (?,?,?,?,?,?)";
let inserts = ["post","post_by_username","title","post_body","posted_date","views","coords",`${username}`,`${postTitle}`,`${postCardArray}`,`${postedDate}`,0,`${coords}`];
query = mysql.format(query,inserts);
pool.getConnection((err,connection) => {
if(err)
throw err
else
connection.query(query,(err,rows) => {
connection.release();
console.log(rows)
})
})

}

但是上面的代码插入这样的数据 [Object] 我不知道如何插入。

最佳答案

在您的示例中,您正在使用新的 ES6 字符串模板,它将在内部调用对象上的 toString 方法,因此您应该检查这部分代码的变量值

`${username}`,`${postTitle}`,`${postCardArray}`,`${postedDate}`,0,`${coords}`

基本上,普通对象的 toString 方法将返回字符串 "[object Object"] 而不是键值对。您还可以查看 JSON.stringify 方法,它将创建对象的 JSON 字符串

我建议您使用 ORM 来构建有效的查询,例如 Sequelize , BookshelfKnexnode-orm2.

关于javascript - 如何使用node js将对象数组插入到mysql中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43329053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com