Search code examples
node.jsmongodbmongoose

How i can delete user and and everything related to him with his id in mongodb?


I am trying to delete a user that has this schema.

const schema = new mongoose.Schema({
  email: {
    type: String,
    lowercase: true,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  user_data: {
    display_name: {
      type: String,
      maxLength: 10,
      default: null,
    },
    avatar: {
      type: String,
      default: "",
    },
    handle: {
      type: String,
      maxLength: 10,
      lowercase: true,
      default: null,
    },
    country: {
      type: String,
      default: null,
      required: true,
    },
    subscriptionID: {
      type: String,
      default: null,
      required: false,
    },
    utype: {
      type: String,
      default: "user",
      enum: ["user_verified", "org_verified", "user"],
      required: true,
      immutable: (doc) => doc.role !== "ADMIN" || doc.role !== "MODERATOR",
    },

    following: [
      {
        _id: {
          type: mongoose.Schema.ObjectId,
          ref: collection,
        },
      },
    ],
    followers: [
      {
        _id: {
          type: mongoose.Schema.ObjectId,
          ref: collection,
        },
      },
    ],
  },
  user_payment: {
    unpoints: {
      type: Number,
      default: 0,
      max: 1999,
      min: 0,
    },
    currency_id: String,
    history: [
      {
        order_id: String,
        metadata: Map,
        purchase_date: {
          type: Date,
          default: Date.now,
        },
      },
    ],
  },
  developer_data: {
    api_key: {
      type: String,
      unique: true,
      default: null,
    },
  },
  email_verified: {
    type: Boolean,
    default: false,
  },
  role: {
    type: String,
    default: "USER",
    enum: ["USER", "MODERATOR", "ADMIN"],
    immutable: (doc) => doc.role !== "ADMIN",
  },
});

also I have this other schema where the publications are stored

const schema = new mongoose.Schema({
  uid: {
    type: mongoose.SchemaTypes.ObjectId,
    ref: userCollection,
  },
  content: { type: String, required: true, maxLength: 250 },
  created_At: {
    type: Date,
    default: Date.now,
  },
  media: Map,
  link: String,
  comments: [
    {
      _id: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: collection,
      },
    },
  ],
});

const snsModel =
  mongoose.models[collection] || mongoose.model(collection, schema);

export default snsModel;

Now what I am looking for is to do the following, when a user deletion request is sent, the backend starts deleting everything related to it. This includes, posts, comments, following and followers. The problem is that this also has to modify the rest of the users, since the other users must be deleted from the user that was deleted (of course, if he follows them).

So, my first solution is to use .post("findOneAndDelete"). then use deleteMany to delete the user's posts, however, now my doubt and problem. How do I do the rest? is there an optimal way to perform the deletion of a user and his data?


Solution

  • Yes, in MongoDB, you can use the concept of cascading delete to remove related data across different collections when a deletion request is made for a particular document. However, it's important to implement this behavior carefully to ensure data integrity and consistency. MongoDB does not provide native cascading delete like some relational databases, so you'll need to handle this at the application level.

    Here's a general approach to achieving cascading deletion in MongoDB:

    -> Identify which collections have relationships with the collection that's being deleted. For instance, you might have a parent-child relationship between two collections where deleting a document from the parent collection should also delete related documents from the child collection.

    -> When you receive a delete request for a document, your application needs to handle the deletion logic. This typically involves:

    Deleting the document from the primary collection. Identifying related collections and deleting associated documents from them. -> If the related deletes need to be atomic (all-or-nothing), you can use MongoDB transactions to ensure data consistency across multiple collections during deletion.