简体   繁体   English

如何使用节点js将对象数组插入mysql?

[英]How to insert array of Object in to mysql with node js?

I am new to node js .I am pretty confused that how to insert array of object in to mysql with nodejs 我是Node js的新手,我很困惑如何使用Node.js将对象数组插入mysql

My Code 我的密码

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

    }

But Above Code inserts the data like this [Object] I don't know how to insert . 但是,上面的代码会像这样[Object]插入数据,我不知道如何插入。

In your example, you are using new ES6 string templateing which internally will call toString method on your object, so you should check your variable values of this part of code 在您的示例中,您正在使用新的ES6字符串模板,该模板内部将在对象上调用toString方法,因此您应检查这部分代码的变量值

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

Basically toString method of plain object will return string "[object Object"] instead of key value pairs. 基本上,普通对象的toString方法将返回字符串"[object Object"]而不是键值对。 Also you can look at JSON.stringify method, which will create JSON string of your object 您也可以查看JSON.stringify方法,该方法将创建对象的JSON字符串

I would suggest you to use ORM instead to build valid queries, such as Sequelize , Bookshelf with Knex or node-orm2 . 我建议您使用ORM来构建有效的查询,例如Sequelize ,带有Knex的 书架node-orm2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM