Use App User ID as Primary Key for Another Collection

Is there a way to use the ID from the App Users collection in Realm as a primary key for another collection? I want to have documents in a second collection be unique to each app user but I’m not sure how to set up the schema for that second collection. Are the IDs in the app users collection bson ObjectIds?

@Gus_McCallum welcome to the community! You can achieve this with Realm functions. If you want the app user’s id to be the primary key of unique documents in a collection I would assume that you are trying to maintain a User collection in Atlas. There are two ways that come to mind you could consider.

Simple Function
In the example below I click a button to create an event. On the frontend I called the function and passed in userId:

userId =

 exports = async function(userId) {
  const mongodb ="mongodb-atlas");
  const myCollection = mongodb.db("dbName").collection("collectionName");
  const newEvent = {
    _id: BSON.ObjectId(userId), 
    eventName: 'Default Event Name',
await myCollection.insertOne(newEvent);

Authentication Trigger
Assuming you have authentication setup. When the user creates an account this gets called immediately.

exports = async function(authEvent) {
  const mongodb ="mongodb-atlas");
  const myCollection = mongodb.db("dbName").collection("collectionName");
  const { user } = authEvent;
  const newUser = {
    _id: BSON.ObjectId(, 
    firstName: '',
    lastName: '',

await myCollection.insertOne(newUser);

Now just add a new trigger that calls this function.

  • Type: Authentication
  • Name: ‘New User (or any string)’
  • Action Type: Create
  • Provider: However the user is authentication (email/password, Facebook, etc.)
  • Event Type: Function
  • Function: ‘Name of Your New User Trigger’

Correction / Clarification
Be mindful setting your document Object IDs to match you app user id if you want to use sync. It is my understanding that you cannot use “_id” as a partition key.

Can clarify or elaborate further if you have a specific use case as well!


be aware of