I am new to node js .I am pretty confused that how to insert array of object in to mysql with nodejs
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 .
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
`${username}`,`${postTitle}`,`${postCardArray}`,`${postedDate}`,0,`${coords}`
Basically toString
method of plain object will return string "[object Object"]
instead of key value pairs. Also you can look at JSON.stringify
method, which will create JSON string of your object
I would suggest you to use ORM instead to build valid queries, such as Sequelize , Bookshelf with Knex or node-orm2 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.