DarkPurple141
DarkPurple141

Reputation: 290

How to properly remove redundant ref Object id after removing a Document

I've come from a relational database background and I'm having a little trouble running into the following pattern on Mongoose.

Say I have SchemaA and SchemaB (let's say pets and people):

const Person = new Schema({
      name: String,
      pets: [{ ref: 'Pet', type: mongoose.Schema.Types.ObjectId}]
})

const Pet = new Schema({
      name:  String,
      owner: { ref: 'Person', type: mongoose.Schema.Types.ObjectId}
})

Now when I do an update that removes a Pet from my database, I need to remove the corresponding ID from my Person's pets array.

This is a slightly contrived example, but what ends up happening often is I have to run findByIdAndRemove() and then filter the id of the removed Pet in the corresponding Person owner.

This feels pretty inefficient and there's I'm sure a better way to do this. Any help much appreciated.

Upvotes: 0

Views: 46

Answers (1)

Thilo
Thilo

Reputation: 262474

In general terms your answer is: MongoDB does not offer transactions that span multiple documents and constraints or triggers to enforce referential integrity. It is up to your application to take care of this (and the data schema may need to change accordingly compared to what you are used to from relational databases).

For the case at hand: Why do you need the pets array in Person in the first place? You can always query the Pet collection by ownerId. That would be my first thought. But it depends on the complete use-case. For example, if you wanted to sort people by number of pets, you probably need to de-normalize like that (and store the same information in multiple places, taking care to keep it in sync).

(Another approach -- and this should have been my first thought actually -- is to not have a Pet collection, but use embedded documents that you collect in the pets array of each Person.)

Upvotes: 1

Related Questions