3

I have this schema in my mongo db.

const movieSchema = new mongoose.Schema({
    title: String,
    year: Number,
    score: Number,
    rating: String
})

When I tried to delete collections with year greater than 1999, I have mistakenly put the condition as:

 Movie.deleteMany({yeaer: {$gte: 1999}}).then(res => {console.log(res)})

This happened This happened

And all of my data got deleted Before and after deletion

ash54321
  • 133
  • 1
  • 9
  • Safe guard your self just as @Christian said but you also misspelt the year (yeaer) in or delete query – Rilla Jun 18 '22 at 12:04
  • Yeah, actually my question was why did it delete everything when i passed down a wrong query with no matching records – ash54321 Jun 18 '22 at 12:21
  • Wow! Deleting everything is scary! In `pymongo`, I tried `delete_many` on a toy collection using your same non-matching filter and fortunately it returned `deleted_count` as `0` and I verified the collection was completely intact. Phew! – rickhg12hs Jun 18 '22 at 14:10

1 Answers1

3

If you omit the conditional property from deleteMany(), mongoose will delete all documents from the model. The same is true if you misspell the conditional. It's a rather dangerous default behaviour but you can guard yourself by disabling strict querying mode in mongoose:

mongoose.set('strictQuery', false)
Christian
  • 169
  • 1
  • 6