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

标签 javascript mysql node.js

我是 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/

相关文章:

node.js - 如何更改/输入 Passport.js 'username' 和 'password' 之外的不同属性

javascript - 如何在 d3 工具提示中添加点击事件?

javascript - 为什么我在使用 jquery ui 自动完成时会得到额外的 html?

javascript - 如何在 Json-server 和 Axios 中使用 delete 方法?

mysql - 如何在mysql中合并多个select

node.js - passport-saml 和 SAML 加密

javascript - 在 Javascript 中检查结果时如何修复 'undefined' 对象?

PHP PDO "select like"查询

php - SQLSTATE[HY000] : General error: 1366 Incorrect integer value:

javascript - 使用 joi 验证整个请求对象