Best Approach to a 3 Table Update for Tagging System in NodeJS and MySQL
<p>I'm writing an application that let's a user post content (called "moments") along with one or more tags associated with that content.</p>

<p>I have a 3 table data model (in MySQL) that looks like this:</p>

<ul>
<li>Table: MOMENTS, Columns: MOMENT_ID, USER_ID, TITLE, CREATE_DATE</li>
<li>Table: TAGS, Columns: TAG_ID, TITLE, CREATE_DATE</li>
<li>Table: MOMENTS_TAGS, Columns: MOMENT_ID, TAG_ID</li>
</ul>

<p>Auto-Increment is set for: MOMENT_ID and TAG_ID</p>

<p><strong>The problem I'm trying to solve (in NodeJS) is: how do I insert a new post (in MOMENT table) and 1 or more tags (in TAGS table), get their respective ID's and do a 3rd insert into the junction table (MOMENT_TAGS)?</strong></p>

<p>I've already attempted to solve this (using mysqljs) by doing 3 successive queries, first MOMENTS, then TAGS, then MOMENTS_TAGS, but it fails because although the first result1.insertId returns the correct number, the 2nd result2.insertId doesn't seem to return the correct number from the TAGS table and instead simply increments the first result1.insertId.</p>

<p>Here is my code so far (I'm trying to get this to work for 1 tag at first):</p>

<pre><code>app.post('/api/post/complex', function(req,res) {

  pool.getConnection(function(err, connection) {

    var preppedQuery1 = "INSERT INTO MOMENTS (USER_ID, TITLE, CREATE_DATE) VALUES ('justatest@gmail.com','test moment title','2016-08-08')";
    connection.query(preppedQuery1, function(err1, result1) { 

      if (err1) {
        res.send('ERROR');  
        connection.release();
      } 
      else {

        var preppedQuery2 = "INSERT INTO TAGS (TITLE, CREATE_DATE,USER_ID) VALUES ('TEST TAG', '2016-09-08','justatest@gmail.com')";
        connection.query(preppedQuery1, function(err2, result2) {  

        if (err2) {
          res.send('ERROR');  
          connection.release();
        } 
        else {

          var preppedQuery3 = "INSERT INTO MOMENTS_TAGS (MOMENT_ID, TAG_ID) VALUES (" + result1.insertId + "," + result2.insertId + ")";
          //At this point if result.insertId is 100, result2.insertId is always 101 instead of coming from the TAGS table
          //Why isn't result2.insertId the auto-incremented number from the TAGS table insert?

connection.query(preppedQuery3, function(err3, result3) {  

            if (err3) {         
              res.send('ERROR');
              connection.release();  
            } 
            else {
              console.log(result3); //not really needed
              res.send('OK'); //everything worked
              connection.release();

            }

          });

        }

        });

      } 

    });

  });

});
</code></pre>