Skip to content

How to Remove Referencing Objects on Deletion in MongoDB

Published: at 08:26 AM

I encountered this issue when I was working on a project that used MongoDB as its database. Working with multiple collections can often lead to this kind of situation. To better understand, here is a brief explanation.

referencing-objects-issue

Let’s jump to the solution:

const employee = Employee.findById("628ajdsf");
const item = Item.findById("6226dh3s");

await employee.remove();

// use $pull to update the field
await item.updateOne({
  $pull: {
    employeeId: employee.id,
  },
});

That’s it. Hope this helps, and see you in the next post!