Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

rails vs node db transactions

General • Asked by Sean M


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?

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.