0
\$\begingroup\$

Just reviewing my own code and noticed that I'm saving info in the DB and WAITING for that to respond before I send info to the browser, although I'm wondering if it would be more performant to not wait...

For example, let's update a user's email address.

Currently, I get a user, update their info, save and wait for confirmation, then send the browser the data:

UserModel.findById(user._id)
  .then(function(user){
    user.email = 'newemail@google.com';
    return user.save();
  })
  .then(function(user){
    res.send(user.email)
  })

But the user data is already edited, and I already have it, so can't I send the browser the data and save to MongoDB at the same time...?

UserModel.findById(user._id)
  .then(function(user){
    user.email = 'newemail@google.com';
    user.save();
    res.send(user.email)
  })

I guess, now that I'm typing it out, the only issue (I can imagine) would be if there was an error with the saving operation at the DB level... How often does that even happen? It's really only a matter of milliseconds, but just wondering if anyone has done this or can share a horror store of why I definitely should not do this.

\$\endgroup\$
  • \$\begingroup\$ What is res? Please clarify. \$\endgroup\$ – 200_success Dec 21 '17 at 6:14
  • \$\begingroup\$ @200_success res seems to be a normal Node.js Response object to me. \$\endgroup\$ – cramopy Dec 21 '17 at 6:23
1
\$\begingroup\$

The big question to ask is: what happens when it doesn’t work? (For whatever reason)

In your case, the user will probably think it worked, only to find out later that it didn’t and will most likely think “stupid app, I just changed this”. You may be okay with it. I wouldn’t. The people paying me probably wouldn’t either.

And what a blessed career you’ve had as a developer if you believe a DB operation failing is such a very rare occurrence. Specially when deployed to production.

\$\endgroup\$
  • \$\begingroup\$ ha ha ha - I've never deployed a full stack app before, so, yeah... Sounds like a pretty definite no-no. Thanks RS \$\endgroup\$ – TJBlackman Dec 21 '17 at 13:56
  • \$\begingroup\$ That explains it. haha Everything breaks down in production: Network issues, server crashes, conflicting versions during upgrades... You should take that into account even when developing locally. \$\endgroup\$ – Rafael Soares Dec 21 '17 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.