Im building a nodejs-app with postgres backend. Im using a pool of connections and when I call my DB like this, I expect the last inserted ID to be returned. This works fine, but the code thats calling the function is getting a undefined returned. What could be the problem here?
function LogSmsToDb(messageToLog) {
const text = 'INSERT INTO sms(Sender, Message, CreateDate) VALUES($1, $2, $3) RETURNING smsid'
var datenow = new Date();
const values = [messageToLog.from, messageToLog.message, datenow]
pool.query(text, values, (err, res) => {
if (err) {
logger.error('Error saving to db: ' + err);
console.log('Error saving to db: ' + err);
return 0;
}
else{
console.log('id' + res.rows[0].smsid) //This gives me the value to console.
return res.rows[0].smsid;
}
})
}
calling code:
routes.post('/newsms', function (req, res) {
let sms = req.body;
var smsId = LogSmsToDb(sms); //Value here is undefined.
}
From What I can see the console output seems to be coming in the wrong order, so my first call to console.log is showing up last.
returned id: undefined [ undefined, '1', 1, 2018-02-12T09:51:09.492Z ] id27
Any ideas?