Navigation

Access Custom User Data

Overview

You can read arbitrary data about your application users, known as custom user data, directly within your Node application. For example, you might store a user’s preferred language, date of birth, or local timezone. You can write to the Custom User Data object via a mongoClient.

The code examples in this page use the following user object on which the custom_data field has not yet been set.

{
  id: '5f1f216e82df4a7979f9da93',
  type: 'normal',
  custom_data: {
    _id: '5f20d083a37057d55edbdd57',
    userID: '5f1f216e82df4a7979f9da93',
    description: 'a test document for user: test@test.com',
  },
  data: { email: 'test@test.com' },
  identities: [
    { id: '5f1f216e82df4a7979f9da90', provider_type: 'local-userpass' }
  ]
}

Note

To use custom user data, you must Enable Custom User Data.

Write to Custom User Data with a MongoClient

Note

To modify the custom data field from a client or user function, write permission to the collection in which custom data is stored must be configured. If you prefer to restrict client write access to custom data from your application, you can still modify the object from a system function.

Using standard CRUD operations through the MongoDB Atlas service, a user’s custom data can be accessed. The following example updates the user’s custom data to alter the user’s favoriteColor to pink.

// A user must be logged in to use a mongoClient
const user = await app.logIn(credentials);
const mongo = user.mongoClient("<atlas service name>");
const collection = mongo.db("<database name>").collection("<collection name>");

const filter = {
  userID: user.id, // Query for the user object of the logged in user
};

const updateDoc = {
  $set: {
    favoriteColor: "pink", // Set the logged in user's favorite color to pink
  },
};

const result = await collection.updateOne(filter, updateDoc);
console.log(result);

Output

{ matchedCount: 1, modifiedCount: 1 }

Read Custom User Data

Custom Data May Be Stale

MongoDB Realm does not dynamically update a user’s custom data if the underlying document changes. Instead, MongoDB Realm fetches a new copy of the data whenever a user refreshes their access token, such as when they log in. This may mean that the custom data won’t immediately reflect changes, e.g. updates from an authentication Trigger. The client SDKs automatically refresh a logged-in user’s access token periodically, so the user’s custom data should never remain stale for more than 30 minutes.

If you have updated your custom user data within the last 30 minutes, use the refreshCustomData() method on the user object.

const customUserData = await user.refreshCustomData()
console.log(customUserData);

If you have not recently updated your custom user data, use the user object’s customData field.

Note

The customData field of the user object is read-only from a Node application.

const customUserData = user.customData
console.log(customUserData);

Output

{
  "_id":"5f233a3ac49aca916792de1d",
  "description":"a test document for user test@test.com",
  "userID":"5f1f298f757611faec901d0f",
  "favoriteColor":"pink"
}

Complete Example

const Realm = require("realm");
const appId = "<your-realm-app-id>"; // Set Realm app ID here.
const appConfig = {
  id: appId,
  timeout: 1000,
};

async function run() {
  let user;
  try {
    const app = new Realm.App(appConfig);

    const credentials = Realm.Credentials.emailPassword(
      "test@test.com",
      "<password>"
    );

    // A user must be logged in to use a mongoClient
    const user = await app.logIn(credentials);
    console.log(user.id);
    const mongo = user.mongoClient("<atlas service name>");
    const collection = mongo.db("<database name>").collection("<collection name>");

    const filter = {
      userID: user.id, // Query for the user object of the logged in user
    };

    const updateDoc = {
      $set: {
        favoriteColor: "pink", // Set the logged in user's favorite color to pink
      },
    };

    const result = await collection.updateOne(filter, updateDoc);
    console.log(result);

    const customUserData = await user.refreshCustomData();
    console.log(customUserData);
  } finally {
    user.logOut();
  }
}
run().catch(console.dir);

Summary

  • You can use custom user data to store information about your application users.
  • The custom user data field of the user object is read-only, and can only be modified to by performing CRUD operations through the Atlas service.