Can't access user document with user level permission with Realm function

I’m trying to use the Realm function to update the user data, When I select the specific user from the Realm function change user and try to get the current user document the document is null but I can get the document with the system user.

Here is my function

exports = async function updateUserPublicData(arg) {
  const cluster = context.services.get('mongodb-atlas');
  const collection = cluster.db('user').collection('public');
  
  const userId = context.user.id
  
  const updatedUser = await collection.findOne({ _id: BSON.ObjectId(userId)  })
  
  return updatedUser;
};

I use Realm authentication and when the user signed I call the Authentication create trigger function and create a new user document and save the user, using the Realm authentication authId for user public document id

Sample user public documentation

User public collection rule

{
  "roles": [
    {
      "name": "owner",
      "apply_when": {
        "_id": "%%user.id"
      },
      "insert": true,
      "delete": true,
      "search": true,
      "write": true,
      "fields": {},
      "additional_fields": {}
    }
  ],
  "filters": [],
  "schema": {
    "title": "Public",
    "bsonType": "object",
    "required": [
      "_id"
    ],
    "properties": {
      "_id": {
        "bsonType": "objectId"
      },
      "createdAt": {
        "bsonType": "date"
      },
      "updatedAt": {
        "bsonType": "date"
      },
      "name": {
        "bsonType": "string"
      },
      "image": {
        "bsonType": "string"
      }
    }
  }
}

For update user function User Authentication I set Application Authentication

I’m I missing something?

Hey Chawki,

user.Id is actually a string, so for now you would have to create a function that converts user.Id to an objectId type and then use it in your rules. You can learn how to implement something like this here.

We’re also planning on adding a convenience expansion like %stringToOid to make this easier in the future.

Hi, @Sumedha_Mehta1 thanks for the response.

As you said user.Id is a string, I tried storing a user with id field as string data type now I can retrieve that user. But I don’t like to set id as a string data type.

I’m new to Realm and I don’t understand how to create a function that converts user.Id to an objectId type and then use it in your rules

Please help me to solve this issue.

There isn’t currently a way to change the _id field on the User object to a string at the moment. If this is a change you need to make, an alternative is to store another field with the same value as the objectId in string format. However, the recommendation is to use the function based rule to convert the objectId to string when using rules.

2 Likes

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