Can we use mongoose queries to delete items like in SQL?

tdd

#1

Question

Can we use mongoose queries to delete items like in SQL?

Answer

Yes, MongoDB has all the capacities of a database like any other and Mongoose implements it through its query methods. To delete you have two options to choose from: deleteOne and deleteMany, lets use our exercise from this lesson to see how this two methods work:

// we have the schema:
const magicItemSchema = new mongoose.Schema({
  item: {
    type: String,
    required: true
  },
  magicalProperty: {
    type: String ,
    required: true
  },
  unitCost: {
    type: Number,
    required: true
  },
  totalUnits: {
    type: Number,
    required: true
  }

})

//and we have the model

const MagicItem = mongoose.model('MagicItem', magicItemSchema);

Now, remember that we have created documents for each one of the items in items.js. so if we wanted to delete one with the item value 'cloak' the only thing we would need to do is:

MagicItem.deleteOne({item: 'cloak'});

Or let’s say we have many items with the 'invulnerability' property, and we wanted to get rid of them all, then we could use:

MagicItem.deleteMany({magicalProperty: "invulnerability"});

Those are the available queries to delete items with Mongoose.