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 = '[email protected]';
 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 = '[email protected]';
 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.

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Dec 21, 2017 at 5:00
\$\endgroup\$
2
  • \$\begingroup\$ What is res? Please clarify. \$\endgroup\$ Commented Dec 21, 2017 at 6:14
  • \$\begingroup\$ @200_success res seems to be a normal Node.js Response object to me. \$\endgroup\$ Commented Dec 21, 2017 at 6:23

1 Answer 1

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.

answered Dec 21, 2017 at 8:12
\$\endgroup\$
2
  • \$\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\$ Commented Dec 21, 2017 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\$ Commented Dec 21, 2017 at 17:47

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.