Home > Blockchain >  mongodb: remove documents in a collection that ref non-existing document in a different collection
mongodb: remove documents in a collection that ref non-existing document in a different collection

Time:12-05

I have zombie documents in collection1 that reference documents which have been deleted from collection2

const collection1 = new Schema({
  title: { type: String },
  date: { type: Date, default: Date.now },
  ref: { type: Schema.Types.ObjectId, ref: 'collection2' }

})

how can I loop through all docs in collection1 and remove any doc that refs a non-existing ObjectId in collection2?

CodePudding user response:

An aggregation solution would be ideal but the following worked for my use case:

const removeZombies = async () => {
  const col1 = await collection1.find({})
  col1.forEach(async item => {
    const colRef = await collection2.findById(item.ref)
    if (colRef === null) {
      collection1.deleteOne({ _id: item._id })
        .then(doc => console.log(doc))
    }
  })
}
  • Related