Updating 2 mongoose schemas in an api call Updating 2 mongoose schemas in an api call mongoose mongoose

Updating 2 mongoose schemas in an api call


The second way it is correct (could be improved running both of them in parallel) I guess the problem is in another place. I don't know which framework you are using but i guess the field _id is from mongoDB and is an ObjectId and looks like that the decoded.id can be an objectId while the one that comes from the request is of course just a string. So I guess it is empty because it does not find any user with that string.

Try do make it an objectId out of that string ( reffering to req.params.user_id in the second query)


The first route you took seems to be fine.

However, as @cdbajorin mentioned, the error "can't send headers that already sent" has nothing to do with mongoose but the fact that you're trying to set the header after sending a response to the client already. (see this lovely answer)

My suggestion would be to make sure that both database calls are successful before you send a response.

You may also want to look into a two phase commit in this situation, as MongoDB does not support traditional DB transactions and you're updating two documents, one at a time. If for some reason either database call fails, a procedure to recover to a stable state should be taken.


The first way can be improved in two ways. One is updating followers field inside the callback of updating following field. The other way is using async-waterfall. I suggest to go with async-waterfall(npm async-waterfall).