Reputation: 135
I am trying to post data to my local sqlite database. The data appears in my database table after POST, but the Promise.resolve()
returns as undefined
, which in turn doesn't give the result back to client. Am I missing something?
Any help would be appreciated. Here is what I got.
module.exports.addAccount = function (data) {
const db_conn = new sqlite3.Database( path.join(__dirname, "../user_database.sql") )
return new Promise( function (resolve, reject) {
db_conn.serialize( function () {
// insert row
db_conn.run("INSERT INTO some_table (username) VALUES (?);", [data.username], function (err,rows) {
if (!err) {
console.log(rows) // always returns undefined
resolve([rows, this.lastID])
} else {
reject(err)
}
})
})
db_conn.close()
})
}
Then:
app.post("/add-row", function (req, res) {
user_info.addAccount(req.body).then( function(response) {
res.json({
rows: response[0], // this is undefined
row_id: response[1] // this is not
})
}).catch(function () {
})
})
Upvotes: 1
Views: 84
Reputation: 126
This may solve your problem:
db_conn.run("INSERT INTO some_table (username) VALUES (?);", ['string'], function (err) {
if (!err) {
db_conn.get("SELECT * FROM some_table WHERE rowid=?", [this.lastID], function(err, rows) {
db_conn.close()
resolve([rows])
})
} else {
reject(err)
}
})
I am assuming rowid
but maybe your table has another primary key. I would also recommend to adopt async/await
rather than Promise to wait your query to finish before closing the connection.
Upvotes: 2