Reputation: 177
Let's say I've got a mongoose document a
that looks like:
{field_1: 0, field_2: 0}
I then write:
a.field_1 = 1;
a.save()
and sometime later, before the save operation is actually complete, we have:
a.field_2 = 1:
a.save()
Does the change I made to field_2
persist? I'm hoping that the returned document of a
, after both have saved, looks like:
{field_1: 1, field_2: 1}
I've tried it on my machine and I do get the results that I want. But I'm worried that it might just be luck and that I might (unlikely) get:
{field_1: 1, field_2: 0}
Due to the fact that the returned document from the initial save overwrites my value of field_2
back to zero before calling the second save.
Can anyone confirm that the second case is not possible and perhaps shed some light on how mongoose deals with this?
Thanks!
Upvotes: 0
Views: 333
Reputation: 3340
and perhaps shed some light on how mongoose deals with this?
How Mongoose deals with .save()
internally is not explained in the docs. But taking a look at the source code, it seems that the same object is being used until some point (before a call to the MongoDB native driver is done), since Javascript objects are passed as reference, maybe the first call would be using the updated object.
But we are speaking here about asynchronous operations, once the information is sent to MongoDB we don't know what will happen until we get the response. I think we should never rely in asynchronous operations like this, you should always wait for the callback called after .save()
is done, and then do the second one.
Can anyone confirm that the second case is not possible
So answering the question, I think the second case could be possible. It's possible that for some reason the first call to MongoDB(before the object is updated) is completed after the second one.
In your local machine usually it is going to be done in the same order you called it. But depending on the environment it could not be executed in the same order, there are many reasons for that.
Upvotes: 1