Search code examples
node.jsmongodbmodelmongoosedbref

Mongoose DBRef remove original schema removal to remove DBRefs and pull out from DBRef Array


In Mongoose,

I can declare Schemas and also I can use

DBRef

which is simply putting ObjectId or an Array of ObjectId

and populate(get) those items.

I think it would be problem when a DBRef removal is needed.

Is there any way to possibly sync removal of DBref?

For example

  1. Removal of a DBRef from an array should remove that of DBRef in other collections and also pull out that DBRef from arrays of DBRef in different collections
  2. Removal of a document (DBRef from this document's Schema) also removes that of DBRef in other collections and also pull out that DBRef from arrays of DBRef in different collections

Are these possible? If so, how can I achieve these? Or any other Model design suggestions?


Solution

  • You can use schema.pre('remove', ... middleware to implement your own cascaded removal of ObjectId references in other collections. this._id identifies the document being removed in your middleware function.