Making several related inserts with Node.js + CoffeeScript + MySQL
Problem
I have a function that inserts a URL and a title into table 'url' of my database. This function obtains the id assigned by MySQL. I'll explain below for what I need it.
# Creates a URL in the database.
create_url = (url, title) ->
connection.connect print_err
connection.query "INSERT IGNORE INTO url SET ?", {urlName: url, urlTitle: title}, (err, result) ->
throw err if err
inserted_id = result.insertId
After I call create_url, I want to call another function of mine, which inserts into table 'dailyUrl'.
create_daily_url = (url) ->
connection.query "INSERT IGNORE INTO dailyUrl SET ?", {url: url}, (err, result) ->
throw err if err
inserted_id = result.insertId
In this case, the parameter url needs to be the 'inserted_id' I obtained in the previous 'create_url' function.
Therefore, my main script should be something like:
create_url("www.test.com", "test")
create_daily_url(inserted_id)
My problem is that I don't know how to obtain the inserted_id from create_url to use it back in the main script. Any help? Thanks in advance.
Solution
You need to call create_daily_url in a callback after create_url. Something like that:
# Creates a URL in the database.
create_url = (url, title,cb) ->
connection.connect print_err
connection.query "INSERT IGNORE INTO url SET ?", {urlName: url, urlTitle: title}, (err, result) ->
throw err if err
inserted_id = result.insertId
cb result if typeof cb == "function" # prevent failures when you call this function without a callback
create_url "www.test.com", "test", (inserted_url)->
create_daily_url inserted_url.id
Indeed, it would be useful if you add a callback to your create_daily_url function.
create_daily_url = (url,cb) ->
connection.query "INSERT IGNORE INTO dailyUrl SET ?", {url: url}, (err, result) ->
throw err if err
inserted_id = result.insertId
cb() if typeof cb == "function"
Discussion
View additional discussion.