I am developing a web application with Node.js and MongoDB / Mongoose. Our most used model, recording, has many subdocuments. Some of them, for example, include Comment, Orders, and Subscribers.
In the client-side application, whenever the user clicks the delete button, he launches an AJAX request on the delete route for this particular comment. The problem I am facing is that when many of these AJAX calls arrive immediately, Mongoose does not work with a "Document not found" error for some (but not all) calls.
This only happens when calls are made quickly and many at a time. I think this is due to the version in Mongoose that causes document conflicts. Our current process for removal:
Record.findById() document using Record.findById()- Remove the subdocument from the corresponding array (using, say,
comment.remove() ) - Call
record.save()
I found a solution in which I can manually update the collection using Record.findByIdAndUpdate , and then using the $pull statement. However, this means that we cannot use any of the mongoose middleware and completely lose version control. And the more I think about it, the more I understand the situations when this happens, and I will have to use Mongoose wrapper functions like findByIdAndUpdate or findAndRemove . The only other solution I can think of is to put an attempt to delete into the while and hope that this works, which seems like a very bad fix.
Using Mongoose covers does not really solve my problem, as it will not allow me to use any middleware or interceptors at all, which is basically one of the huge benefits of using Mongoose.
Does this mean that Mongoose is practically useless for anything with quick editing, and I could just use my own MongoDB drivers? Do I misunderstand the limitations of Mongoose? How can I solve this problem?
source share