Using realm, I want to ensure a user can only see documents created by them for security reasons. I add a _partition key to each document with the user's id as its value.
I currently do this to display transactions:
const transactions = useQuery(Transaction, transaction => {
return transaction.sorted('date')
})
However, this shows all existing transactions meaning anyone can see anyones transactions. I have explored MongoDB's docs but cannot see anything about it.
I am using realm in react native.
In MongoDB Atlas, enter your Realm application. Navigate to "Rules" and create a collection for your relevant existing database and existing collection name. For example, select the database named "Test" and a collection named "UserData". It is worth noting that these collections should already exist prior to creating them under "Rules". Note that you will need to do the above and below for every collection that requires only the user to be able to read and write their own data. So if you have three collections (Product: public, User: private, and Order: private), you should do the above and below steps for "User" and "Order", but not Product as it is meant to be publicly accessible.
Once this collection is created under "Rules", add a role to it. Select "Other presets" and choose readOwnWriteOwn and add the preset role. Under document permissions, you will see Read and Write JSON files. Here you will enter the property name used to identify a document as a user's and access the user's ID from Realm with "%%user.id". For example, if you use userId to identify a document belongs to a user, use this in both Read and Write:
{
"userId": "%%user.id"
}
Now fill in any other requested information and create the role. Then test that everything is working as desired before going into production. Ensure users truly can only read and write their own data while others cannot.