Catastrophic MongoDB + Mongoose Data Loss
I am running MongoDB in production. Today I woke up to one of my collections of documents completely deleted. Fortunately, I have data backups, and this is not a huge project, but the reason is still a mystery to me.
The code works fine for 6 months without any problem. Everything from one of my collections was deleted at 10 am today.
This is a journal entry. I am replacing the db name and collection name with "myDB" and "cars".
2017-06-04T10:46:43.412+0200 I COMMAND [conn203614] command myDB.$cmd command: delete { delete: "cars", deletes: [ { q: {}, limit: 0 } ], ordered: true, writeConcern: { w: 1 } } keyUpdates:0 writeConflicts:0 numYields:0 reslen:40 locks:{ Global: { acquireCount: { r: 26393, w: 26393 } }, Database: { acquireCount: { w: 26393 } }, Collection: { acquireCount: { w: 26393 } } } protocol:op_query 52921ms
At first I actually believed that the database could have been attacked because
delete { delete: "cars", deletes: [ { q: {}, limit: 0 } ] }
Looked pretty cruel and frank. No where in my code I am running delete {}. But now I have looked through everything and there is a specific case where I delete all "cars" in a collection that match a specific query (owned by the user). I think this is where the error could have occurred, but I just don't understand how. This is the code in question. I have changed the query for "user.find" in this example, but I assure you that it is no more complicated.
models.user.find( { something: "cool"}, '_id', function(err,result)
{
result.forEach(function(user) {
models.car.remove({owner:user._id},function(err){if(err) console.log(err)})
})
});
So, basically, the important line that I think caused the problem:
models.car.remove({owner:user._id}, ... )
This has been working for months and has never worked until today. My first suspicion was obviously that the user object was erroneous, for example user.id was undefined. So, I am testing:
models.car.remove({owner:undefined}, ... )
And it doesn't delete anything or throw an error. HOWEVER Obviously when I run
models.car.remove({}, ... )
Discards the contents of the collection. It also generates an accurate log entry, so I believe this code caused the error. Something must have affected {owner: user._id} to become the equivalent of {}.
I just don't understand how to do it. Indeed, to quickly fix this problem, any help is appreciated.
source to share
No one has answered this question yet
Check out similar questions: