Doc available only for two users?

Hey everyone! I got stuck on making a document available for two users only. My partition is friendshipUsers=userId1+userId2. In a backend function I check if user’s Id is contained in the partition and then I give read/write permissions. However the problem is with opening a realm in the client.

A hacky solution would be to check if the client had issues connecting to realm with partition user1+user2 and if so then try with user2+user1.

Another thing I can do I suppose is duplicate the document so each user access their own doc and update each one with function when there is a change.

Is there a way to have two user read and write to the same document by checking their ids?

Thanks :slight_smile:

Hi @dimo,
Could you sort the user ids in the partition (so that the order in the partition string is deterministic?)

Hey @Andrew_Morgan,

This is how I create the document:

private func request() {
    do {
        try friendshipRealm.write {
            var newFriendship = Friendship()
            newFriendship = Friendship(partition: "friendshipUsers=\(state.user!._id)+\(publicUser._id)",
                                       requester: state.user!._id,
                                       receiver: publicUser._id,
                                       between: [state.user!._id, publicUser._id],
                                       accepted: false)
            type = .cancel
    } catch {
        state.error = "Unable to request friendship"

This is how I open the realm:

var body: some View {
        FriendButton(publicUser: user)
            .environment(\.realmConfiguration, app.currentUser!
                .configuration(partitionValue: "friendshipUsers=\(state.user!._id)+\(user._id)"))

The partition is always requester+receiver. I wonder if I am doing the whole thing in a wrong way. Would you recommend to duplicate the document for each user?

I’m assuming that your issue is that each of the 2 friends is using a different ordering of users in the partition key? If so, then you could get around that problem by always using something like…

  "friendshipUsers=\(min(state.user!._id, user._id))+\(max(state.user!._id, user._id))"))

The same logic would be applied when creating the object. That way both users would use the same partition name for the relationship.

Alternatively, you could duplicate the data and then user the user id as the partition (that may mean that the app would open fewer partitions which could help with performance)


Worked perfectly! I need to learn more about swift I guess…

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.