Search code examples
node.jsmongodbsocketsmongoosereal-time

Mongoose Schema Post 'save' callback ordering


I'm using the mongoose Schema.post('save', postSaveCallback) method in order to send updates over a socket to display the state of the world in the database to subscribed clients in a web browser. I am wondering if the post save callback is guaranteed to be executed in the same order that the save method was called? This would guarantee that the state represented in the client view is the accurate state of the world. If the ordering of these post save callbacks is not guaranteed to be in the same order that the mongoose save method is called, it would mean that the clients view could potentially get out of sync with the real database representation.

Is there a better way to do this or is my approach sensible?

Furthermore, is it guaranteed that when postSaveCallback is called the save operation on the underlying mongodb has fully completed and was successful?

Would be very grateful for any pointers on this.

Thanks in advance.


Solution

  • As with async things in general, order is not defined. The postSaveCallback is called when the save operation returns and then is executed when Node gets around to it. Some saves take longer than others which may have been kicked off before, so the callbacks could occur in pretty much any order. You'll have to modify how your callbacks coordinate with each other to ensure whatever kind of consistency you require in your state.

    The save callback takes an err argument, so naturally just because the callback doesn't mean that the operation succeeded.