Search code examples
node.jsexpressbookshelf.jsknex.js

get the last record id using bookshelf.js/knex.js[mysql] + express.js


for example, if I have 2 tables(invoices , bills items which include the quantity ) connected to each other through a one to many relationships . and a post api gives me the data . the new bill id will be the last id+1 so if I can make a loop that will make the objects be inserted then run

  knex.insert(arrayPurchaseItems, 'id').into('purchaseRequests').then()

so I don't need to wait for the bill insertion to be resolved however, the risk of the purchase request insertion starting before bill inserting completion exist . any ideas ??


Solution

  • on such scenarios you should make sure your db already have the parent entity stored. It's just simpler than handle with the odds of concurrent access, latency and so on.

    for example an idiom like this could be useful in this case:

    router.post("/save-master-detail",function(req,res){
      var payload = req.body // make sure to have bodyParser all set on express
      var master = payload.master
      var details = payload.details
      knex("master").insert(master,"idmaster").then(function(ret){
        master.idmaster = ret[0]
        details = details.map(function(det){
          det.idmaster = master.idmaster
          return det
        })
        return knex("detail").insert(details)
      }).then(function(){
        res.send("OK") // or any kind of meaningful response
      }).catch(function(err){
        console.log(err)
        res.status(500).send(err)
      })
    })