All threads / rails vs node db transactions

Ask A Question


You’re not receiving notifications from this thread.

rails vs node db transactions

Sean M asked in General


I am playing around with node.js and see promises everywhere even with db transactions. I was wondering why it is so different from rails.

For instance:

var db  = require('mongodb-promises').db('host:port', 'db_name'),
todoColl = db.collection('todos');

todoColl.insert({text: 'first task to do '})
  .then(function (result) {
    console.log('saved successfully');
  .catch(function (err) {
    console.error('Error on insert ', err);

in rails this would be something like

@todo =
@todo.text = "first task to do"
  render :json, @todo //I am not sure if format type matters in this example
  render json: @todo.errors, status: :unprocessable_entity

From my understanding (the following must be wrong somewhere, pls correct me):

Rails db transactions are synchronous and if in controller is equivalent with after_save AR callback in the model, so rendering in controller fires after the validation is done and object is saved, BUT before it's committed to the database.

So basically we don't read the todo object from db after it gets there (since it's not committed yet), but we use @todo ivar which contains the knowledge to render html/json if data is valid and saved. Then if something goes wrong with the transaction then everything get's rolled back, so no problem. And we use after_commit instead of after_save in rails if we need some data that we wanna read back from db to make sure the data is already there (for instance elasticsearch indexing).

But my explanation must be wrong somewhere since if this is synchronous then we have to wait for the db transaction anyway, so we could use for instance if @todo.committed (this is just imaginary) or Todo.find(params( instead of if

I. question:

Could you tell me where my explanation goes wrong?

II. As for node.js question:

Could you explain me why db transactions are handled asynchronously in node.js unlike in rails?

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 41,443+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.