delete records from multiple collections on the basis of value present in MainCollection (mongoose) Express.js

Issue

Hello everyone I’m new to mongo and i’m stuck on something. I’m creating a expense tracker using react.js express.js and mongodb.

I’ve 2 collections : TrancstionSchema

const schema = mongoose.Schema({
    title: String,
    createdDate: Date,
    amount:Number,
    expenseType:String,
    category:String
})

Category Schema

const schema = mongoose.Schema({
    title: String,
    createdDate: Date,
})

If user delete a Category it should remove it’s records from Category schema and transactions schema

Categorylist

as you can see that Category List title is referenced to transactionList as a category

enter image description here

**

If User delete a category it record should be deleted from both
collections categoryList and transaction list .

** Please help with a code sample

Solution

You can define a middleware function to run automatically after your category schema remove operation:

// Category schema
const schema = mongoose.Schema({
  title: String,
  createdDate: Date,
})

schema.post('remove', async (doc, next) => {
  // Delete all records from transaction schema with category
  await Transaction.deleteMany({ category: doc.title })
  // OR Update the category of transactions to empty string
  await Transaction.updateMany({ category: doc.titleĀ }, { category: '' })
  next()
})

Calling the remove function on a category document will automatically delete all transaction with the same category associated:

await category.remove();

Answered By – lpizzinidev

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published