MongoDb atlas app service Rules how to filter soft delete

This is my rules

{
  "filters": [
    {
      "name": "user",
      "query": {
        "userId": "%%user.id",
        "deletedAt": null
      },
      "projection": {},
      "apply_when": {
        "%%user.custom_data.role": "user"
      }
    }
  ],
  "roles": [
    {
      "name": "admin",
      "apply_when": {
        "%%user.custom_data.role": "admin"
      },
      "document_filters": {
        "write": true,
        "read": true
      },
      "read": true,
      "write": true,
      "insert": true,
      "delete": true,
      "search": true
    },
    {
      "name": "user",
      "apply_when": {},
      "document_filters": {
        "write": {
          "userId": "%%user.id"
        },
        "read": {
          "userId": "%%user.id",
          "deletedAt": null
        }
      },
      "read": true,
      "write": true,
      "insert": true,
      "delete": false,
      "search": true
    }
  ]
}

I want to show not deleted data only to user, admin can see all data including deleted data. This above code return deleted data to user. If I want to query not deleted data, I need to add deletedAt: null to write permission of document filters which caused user cannot write deletedAt field. Is there any solution to this?

Hello,

I’m no expert but since I had recently the same kind of issue I’ll share what I’ve learned :

  • Even if read is false, the user will be able to read it if write evaluates to true
    That explains why deleted data can be read by user in your example

  • The write permission is evaluated AFTER the transaction. If you have deletedAt : null as write condition, then any modification by user that makes deletedAt non null will be immediately reverted.

I don’t think there is a way for a user to lose write permission using only rules. A solution could be to filter at application level instead, when subscribing.