Docs Menu
Docs Home
/ /
Atlas Device SDKs
/

Custom User Data

On this page

  • Prerequisites
  • Create Custom User Data
  • Read Custom User Data
  • Update Custom User Data
  • Delete Custom User Data

This page describes custom user data in an App Services App and how to manage it with Atlas Device SDK.

Atlas App Services lets you associate data with an authenticated user, such as a user's preferred language, date of birth, or local timezone. You can store this arbitrary custom user data about your users and read it from your client application.

To use custom user data, you must have an App Services App with custom user data enabled.

To set up an App Services App that uses custom user data, refer to the following:

  1. Enable Custom User Data in the App Services documentation

  2. Connect to Atlas

When you configure custom user data in Atlas, you designate a database and collection to store the custom user data. This data is stored as documents in Atlas.

To create custom user data for a user, create a MongoDB document in the custom user data collection. The user ID field of the document should contain the user's user ID. You can create custom user data documents in a few ways:

  • Define a User Creation Function that automatically creates custom user data as part of the user registration process.

  • Define a Function that you call with the user data, perhaps sometime after registration.

  • Access MongoDB through the SDK, if your language supports it, and insert a document directly into the custom user data collection.

  • Manually create a custom data document through:

Tip

In the App Services UI, check the App Users page under the Custom User Data tab to find and configure custom user data settings, including:

  • The custom user data cluster, database, and collection

  • The user ID field used to map custom user data documents to users

In this example, we use an Atlas Function to create the custom user data. The Function takes an object passed by the client add adds it to the custom user data collection in Atlas. The Function creates the custom user data if it doesn't already exist and replaces all data in it if it does exist.

updateCustomUserData.js - Atlas Function running on server (JavaScript)
exports = async function updateCustomUserData(newCustomUserData) {
const userId = context.user.id;
const customUserDataCollection = context.services
.get("mongodb-atlas")
.db("custom-user-data-database")
.collection("cpp-custom-user-data");
const filter = { userId };
// Replace the existing custom user data document with the new one.
const update = { $set: newCustomUserData };
// Insert document if it doesn't already exist
const options = { upsert: true };
const res = await customUserDataCollection.updateOne(filter, update, options);
return res;
};

The following example calls a function to insert a document containing the user ID of the currently logged in user and a favoriteColor value into the custom user data collection.

The following example uses MongoDB Data Access to insert a document containing the user ID of the currently logged in user and several custom properties into the custom user data collection:

app = App.Create(myRealmAppId);
user = await app.LogInAsync(Credentials.Anonymous());
mongoClient = user.GetMongoClient("mongodb-atlas");
dbTracker = mongoClient.GetDatabase("tracker");
userDataCollection = dbTracker.GetCollection<CustomUserData>("user_data");
var cud = new CustomUserData(user.Id)
{
FavoriteColor = "pink",
LocalTimeZone = "+8",
HasPets = true
};
var insertResult = await userDataCollection.InsertOneAsync(cud);

You may find it helpful to create a C# class (POCO) that represents the custom user data object. The SDK will serialize/deserialize this class to and from BSON when writing, reading, and updating properties. The example above uses the following class to map the properties.

This example uses an Atlas Function to create the custom user data document. The Atlas Function takes an object passed by the client add adds it to the custom user data collection in Atlas. The Function creates the custom user data if it doesn't already exist and replaces all data in it if it does exist.

writeCustomUserData.js - Atlas Function running on server (JavaScript)
exports = async function writeCustomUserData(newCustomUserData) {
const userId = context.user.id;
const customUserDataCollection = context.services
.get("mongodb-atlas")
.db("custom-user-data-database")
.collection("custom-user-data");
const filter = { userId };
// Replace the existing custom user data document with the new one.
const update = { $set: newCustomUserData };
// Insert document if it doesn't already exist
const options = { upsert: true };
const res = await customUserDataCollection.updateOne(filter, update, options);
return res;
};

The client calls the Function to create the user data.

The following example uses MongoDB Data Access to insert a document containing the user ID of the currently logged in user and a favoriteColor value into the custom user data collection.

This example calls an Atlas Function to create custom user data. In this example, the Atlas Function takes an object passed by the client and adds it to the custom user data collection in Atlas. The Function creates the custom user data if it doesn't already exist and replaces all data in it if it does exist.

writeCustomUserData.js - Atlas Function running on server (JavaScript)
exports = async function writeCustomUserData(newCustomUserData) {
const userId = context.user.id;
const customUserDataCollection = context.services
.get("mongodb-atlas")
.db("custom-user-data-database")
.collection("custom-user-data");
const filter = { userId };
// Replace the existing custom user data document with the new one
const update = { $set: newCustomUserData };
// Insert document if it doesn't already exist
const options = { upsert: true };
const res = await customUserDataCollection.updateOne(filter, update, options);
return res;
};

The Kotlin SDK uses the following code to call this Function.

The following example uses MongoDB Data Access to insert a document containing the user ID of the currently logged in user and a favoriteColor value into the custom user data collection.

The following example accesses MongoDB through the MongoClient to insert document a into the custom user data collection. This document contains the user ID of the currently logged in user and a favoriteColor value.

The following example accesses MongoDB through the MongoClient to insert document a into the custom user data collection. This document contains the user ID of the currently logged in user and a favoriteColor value.

auto user = app.login(realm::App::credentials::anonymous()).get();
// Functions take a string argument. Any quotes within the array must be
// escaped.
auto customData =
"[{\"userId\":\"" + user.identifier() + "\",\"favoriteColor\":\"gold\"}]";
// Call an Atlas Function to insert custom data for the user
auto result = user.call_function("updateCustomUserData", customData).get();
public class CustomUserData
{
public string _id { get; private set; }
public string _partition { get; private set; }
public string FavoriteColor { get; set; }
public string LocalTimeZone { get; set; }
public bool HasPets { get; set; }
public CustomUserData(string id, string partition = "myPart")
{
this._id = id;
this._partition = partition;
}
}
final user = app.currentUser!;
final updatedTimestamp = DateTime.now().millisecondsSinceEpoch;
final updatedCustomUserData = {
"userId": user.id,
"favoriteFood": "pizza",
"lastUpdated": updatedTimestamp
};
final functionResponse = await user.functions
.call("writeCustomUserData", [updatedCustomUserData]);
// Contains the `updatedCustomUserData` object just added
// in the above Atlas Function call
final customUserData = await user.refreshCustomData();
Credentials credentials = Credentials.anonymous();
app.loginAsync(credentials, it -> {
if (it.isSuccess()) {
User user = app.currentUser();
MongoClient mongoClient =
user.getMongoClient("mongodb-atlas"); // service for MongoDB Atlas cluster containing custom user data
MongoDatabase mongoDatabase =
mongoClient.getDatabase("custom-user-data-database");
MongoCollection<Document> mongoCollection =
mongoDatabase.getCollection("custom-user-data-collection");
mongoCollection.insertOne(
new Document("user-id-field", user.getId()).append("favoriteColor", "pink").append("_partition", "partition"))
.getAsync(result -> {
if (result.isSuccess()) {
Log.v("EXAMPLE", "Inserted custom user data document. _id of inserted document: "
+ result.get().getInsertedId());
} else {
Log.e("EXAMPLE", "Unable to insert custom user data. Error: " + result.getError());
}
});
} else {
Log.e("EXAMPLE", "Failed to log in anonymously:" + it.getError().toString());
}
});
// The documentation does not currently have this code example in JavaScript.
// Please refer to the other languages or related pages for example code.
// Write the custom user data through a call
// to the `writeCustomUserData` function
val functionResponse = user.functions
.call<BsonDocument>("writeCustomUserData",
mapOf("userId" to user.id, "favoriteColor" to "blue")
)
// Refreshed custom user data contains updated
// `favoriteColor` value added in above Atlas Function call
user.refreshCustomData()
val updatedUserData = user.customDataAsBsonDocument()
val anonymousCredentials: Credentials = Credentials.anonymous()
app.loginAsync(anonymousCredentials) {
if (it.isSuccess) {
val user = app.currentUser()
val mongoClient : MongoClient =
user?.getMongoClient("mongodb-atlas")!! // service for MongoDB Atlas cluster containing custom user data
val mongoDatabase : MongoDatabase =
mongoClient.getDatabase("custom-user-data-database")!!
val mongoCollection : MongoCollection<Document> =
mongoDatabase.getCollection("custom-user-data-collection")!!
mongoCollection.insertOne(Document("user-id-field", user.id).append("favoriteColor", "pink").append("_partition", "partition"))
.getAsync { result ->
if (result.isSuccess) {
Log.v("EXAMPLE", "Inserted custom user data document. _id of inserted document: ${result.get().insertedId}")
} else {
Log.e("EXAMPLE", "Unable to insert custom user data. Error: ${result.error}")
}
}
} else {
Log.e("EXAMPLE", "Failed to log in anonymously: ${it.error}")
}
}
RLMApp *app = [RLMApp appWithId:YOUR_APP_ID];
[app loginWithCredential:[RLMCredentials anonymousCredentials] completion:^(RLMUser *user, NSError *error) {
if (error != nil) {
NSLog(@"Failed to log in: %@", error);
return;
}
RLMMongoClient *client = [user mongoClientWithServiceName:@"mongodb-atlas"];
RLMMongoDatabase *database = [client databaseWithName:@"my_database"];
RLMMongoCollection *collection = [database collectionWithName:@"users"];
[collection insertOneDocument:
@{@"userId": [user identifier], @"favoriteColor": @"pink"}
completion:^(id<RLMBSON> newObjectId, NSError *error) {
if (error != nil) {
NSLog(@"Failed to insert: %@", error);
}
NSLog(@"Inserted custom user data document with object ID: %@", newObjectId);
}];
}];
let appId = YOUR_APP_SERVICES_APP_ID // replace this with your App ID
let app = App(id: appId)
app.login(credentials: Credentials.anonymous) { (result) in
switch result {
case .failure(let error):
print("Failed to log in: \(error.localizedDescription)")
case .success(let user):
let client = user.mongoClient("mongodb-atlas")
let database = client.database(named: "my_database")
let collection = database.collection(withName: "users")
// Insert the custom user data object
collection.insertOne([
"userId": AnyBSON(user.id),
"favoriteColor": "pink"
]) { (result) in
switch result {
case .failure(let error):
print("Failed to insert document: \(error.localizedDescription)")
case .success(let newObjectId):
print("Inserted custom user data document with object ID: \(newObjectId)")
}
}
}
}
// The documentation does not currently have this code example in TypeScript.
// Please refer to the other languages or related pages for example code.

You can add any number of arbitrary fields and values to the custom user data document when you create it. The user ID field is the only requirement for the document to become available on the User object as custom user data.

You can read the custom user data of a currently logged-in user through that user's User object. You cannot edit custom user data through a User object. To edit custom user data, see the Update Custom User Data section on this page.

To read the data, access the custom_data property on the User object of a logged-in user.

To read custom user data, call the GetCustomData() method on the User object of a logged in user.

To read custom user data, call the User.getCustomData() method on the User object of a logged in user.

You retrieve custom user data in the customData property of the User object.

You can read the custom user data of a currently logged-in user using the User.customDataAsBsonDocument() extension function.

To read custom user data, call the User.getCustomData() method on the User object of a logged in user.

To read the data, access the customData property on the User object of a logged-in user.

To read the data, access the customData property on the User object of a logged-in user.

You retrieve custom user data in the customData property of the User object.

// Custom user data could be stale, so refresh it before reading it
user.refresh_custom_user_data().get();
auto userData = user.custom_data().value();
/* Parse the string custom data to use it more easily in your code.
In this example, we're using the nlohmann/json library, but use whatever
works with your application's constraints. */
auto userDataObject = nlohmann::json::parse(userData);
CHECK(userDataObject["favoriteColor"] == "gold");
await user.RefreshCustomDataAsync();
// Tip: define a class that represents the custom data
// and use the gerneic overload of GetCustomData<>()
var customUserData = user.GetCustomData<CustomUserData>();
Console.WriteLine($"User has pets: {customUserData.HasPets}");
Console.WriteLine($"User's favorite color is {customUserData.FavoriteColor}");
Console.WriteLine($"User's timezone is {customUserData.LocalTimeZone}");
final customUserData = user.customData;
Credentials anonymousCredentials = Credentials.anonymous();
app.loginAsync(anonymousCredentials, it -> {
if (it.isSuccess()) {
Log.v("EXAMPLE", "Successfully authenticated anonymously.");
User user = app.currentUser();
Document customUserData = user.getCustomData();
Log.v("EXAMPLE", "Fetched custom user data: " + customUserData);
} else {
Log.e("EXAMPLE", it.getError().toString());
}
});
const customUserData = app.currentUser.customData;
console.log(customUserData);
val user = app.currentUser!!
val customUserData = user.customDataAsBsonDocument()
val anonymousCredentials: Credentials = Credentials.anonymous()
app.loginAsync(anonymousCredentials) {
if (it.isSuccess) {
Log.v("EXAMPLE", "Successfully authenticated anonymously.")
val user = app.currentUser()
val customUserData : Document? = user?.customData
Log.v("EXAMPLE", "Fetched custom user data: $customUserData")
} else {
Log.e("EXAMPLE", it.error.toString())
}
}
RLMApp *app = [RLMApp appWithId:YOUR_APP_ID];
[app loginWithCredential:[RLMCredentials anonymousCredentials] completion:^(RLMUser *user, NSError *error) {
if (error != nil) {
NSLog(@"Failed to log in: %@", error);
return;
}
// If the user data has been refreshed recently, you can access the
// custom user data directly on the user object
NSLog(@"User custom data: %@", [user customData]);
// Refresh the custom data
[user refreshCustomDataWithCompletion:^(NSDictionary *customData, NSError *error) {
if (error != nil) {
NSLog(@"Failed to refresh custom user data: %@", error);
return;
}
NSLog(@"Favorite color: %@", customData[@"favoriteColor"]);
}];
}];
let appId = YOUR_APP_SERVICES_APP_ID // replace this with your App ID
let app = App(id: appId)
app.login(credentials: Credentials.anonymous) { (result) in
switch result {
case .failure(let error):
print("Failed to log in: \(error.localizedDescription)")
case .success(let user):
// If the user data has been refreshed recently, you can access the
// custom user data directly on the user object
print("User custom data: \(user.customData)")
// Refresh the custom user data
user.refreshCustomData { (result) in
switch result {
case .failure(let error):
print("Failed to refresh custom data: \(error.localizedDescription)")
case .success(let customData):
// favoriteColor was set on the custom data.
print("Favorite color: \(customData["favoriteColor"] ?? "not set")")
return
}
}
}
}
// The documentation does not currently have this code example in TypeScript.
// Please refer to the other languages or related pages for example code.

Warning

Custom Data May Be Stale

Atlas App Services does not dynamically update the value of the client-side user custom data document immediately when underlying data changes. Instead, App Services fetches the most recent version of custom user data whenever a user refreshes their access token, which is used by most SDK operations that contact the App Services backend. If the token is not refreshed before its default 30 minute expiration time, the SDK refreshes the token on the next call to the backend. Custom user data could be stale for up to 30 minutes plus the time until the next SDK call to the backend occurs.

Note

If you require the most recent version of custom user data, use the refresh_custom_user_data() function to request the latest version of a user's custom data.

Note

If you require the most recent version of custom user data, call the RefreshCustomDataAsync() method to request the latest version of a user's custom data.

Note

If you require the most recent version of custom user data, use the refreshCustomData() method to request the latest version of a user's custom data.

Note

If you require the most recent version of custom user data, use the User.refreshCustomData() method to request the latest version of a user's custom data.

Note

If you require the most recent version of custom user data, use the User.refreshCustomData() method to request the latest version of a user's custom data.

Note

If you require the most recent version of custom user data, use the User.refreshCustomData() method to request the latest version of a user's custom data.

Note

If you require the most recent version of custom user data, use the User.refreshCustomData() method to request the latest version of a user's custom data.

Note

If you require the most recent version of custom user data, use the refreshCustomDataWithCompletion method to request the latest version of a user's custom data.

Note

If you require the most recent version of custom user data, use the refreshCustomData() method to request the latest version of a user's custom data.

Note

If you require the most recent version of custom user data, use the User.refreshCustomData() method to request the latest version of a user's custom data.

You can update custom user data in a few ways:

  • Define a Function that you call with the updated user data.

  • Access MongoDB through the SDK, if your language supports it, and update the user data document in the custom user data collection directly.

  • Manually update a custom data document through:

To update a user's custom user data with an Atlas Function, edit the MongoDB document whose user ID field contains the user ID of the user. The following example calls the same function used to create the custom user data document above. Here, we update the favoriteColor field of the the document containing the user ID of the currently logged in user.

The following example finds and updates the data by using the UpdateOneAsync() method, and then refreshes the data to ensure the latest changes are available.

This example uses an Atlas Function to update the custom user data document. The Atlas Function takes an object passed by the client add adds it to the custom user data collection in Atlas. The Function creates the custom user data if it doesn't already exist and replaces all data in it if it does exist.

writeCustomUserData.js - Atlas Function running on server (JavaScript)
exports = async function writeCustomUserData(newCustomUserData) {
const userId = context.user.id;
const customUserDataCollection = context.services
.get("mongodb-atlas")
.db("custom-user-data-database")
.collection("custom-user-data");
const filter = { userId };
// Replace the existing custom user data document with the new one.
const update = { $set: newCustomUserData };
// Insert document if it doesn't already exist
const options = { upsert: true };
const res = await customUserDataCollection.updateOne(filter, update, options);
return res;
};

The client calls the Function to update the user data.

The following example uses MongoDB Data Access to update the favoriteColor field of the document containing the user ID of the currently logged in user in the custom user data collection.

This example uses MongoDB remote access to update a user's custom data. The following example updates the custom data to alter the user's favoriteColor to pink.

This example calls an Atlas Function to update custom user data. In this example, the Atlas Function takes an object passed by the client and adds it to the custom user data collection in Atlas. The Function creates the custom user data if it doesn't already exist and replaces all data in it if it does exist.

writeCustomUserData.js - Atlas Function running on server (JavaScript)
exports = async function writeCustomUserData(newCustomUserData) {
const userId = context.user.id;
const customUserDataCollection = context.services
.get("mongodb-atlas")
.db("custom-user-data-database")
.collection("custom-user-data");
const filter = { userId };
// Replace the existing custom user data document with the new one
const update = { $set: newCustomUserData };
// Insert document if it doesn't already exist
const options = { upsert: true };
const res = await customUserDataCollection.updateOne(filter, update, options);
return res;
};

The Kotlin SDK uses the following code to call this Function.

The following example uses MongoDB Data Access to update the favoriteColor field of the document containing the user ID of the currently logged in user in the custom user data collection.

To update a user's custom user data with MongoDB Data Access, edit the MongoDB document whose user ID field contains the user ID of the user. The following example uses MongoDB Data Access to update the favoriteColor field of the the document containing the user ID of the currently logged in user in the custom user data collection.

To update a user's custom user data with MongoDB Data Access, edit the MongoDB document whose user ID field contains the user ID of the user. The following example uses MongoDB Data Access to update the favoriteColor field of the the document containing the user ID of the currently logged in user in the custom user data collection.

// Functions take a string argument. Any quotes within the array must be
// escaped.
auto updatedData = "[{\"userId\":\"" + user.identifier() +
"\",\"favoriteColor\":\"black\"}]";
// Call an Atlas Function to update custom data for the user
auto updateResult =
user.call_function("updateCustomUserData", updatedData).get();
// Refresh the custom user data before reading it to verify it succeeded
user.refresh_custom_user_data().get();
auto updatedUserData = user.custom_data().value();
/* Parse the string custom data to use it more easily in your code.
In this example, we're using the nlohmann/json library, but use whatever
works with your application's constraints. */
auto updatedUserDataObject = nlohmann::json::parse(updatedUserData);
CHECK(updatedUserDataObject["favoriteColor"] == "black");
var updateResult = await userDataCollection.UpdateOneAsync(
new BsonDocument("_id", user.Id),
new BsonDocument("$set", new BsonDocument("HasPets", false)));
await user.RefreshCustomDataAsync();
var customUserData = user.GetCustomData<CustomUserData>();
Console.WriteLine($"User has pets: {customUserData.HasPets}");
Console.WriteLine($"User's favorite color is {customUserData.FavoriteColor}");
Console.WriteLine($"User's timezone is {customUserData.LocalTimeZone}");
final user = app.currentUser!;
final updatedTimestamp = DateTime.now().millisecondsSinceEpoch;
final updatedCustomUserData = {
"userId": user.id,
"favoriteFood": "pizza",
"lastUpdated": updatedTimestamp
};
final functionResponse = await user.functions
.call("writeCustomUserData", [updatedCustomUserData]);
// Contains the `updatedCustomUserData` object just added
// in the above Atlas Function call
final customUserData = await user.refreshCustomData();
Credentials credentials = Credentials.anonymous();
app.loginAsync(credentials, it -> {
if (it.isSuccess()) {
User user = app.currentUser();
MongoClient mongoClient =
user.getMongoClient("mongodb-atlas"); // service for MongoDB Atlas cluster containing custom user data
MongoDatabase mongoDatabase =
mongoClient.getDatabase("custom-user-data-database");
MongoCollection<Document> mongoCollection =
mongoDatabase.getCollection("custom-user-data-collection");
mongoCollection.updateOne(
new Document("user-id-field", user.getId()), new Document("favoriteColor", "cerulean"))
.getAsync(result -> {
if (result.isSuccess()) {
if (result.get().getModifiedCount() == 1L) {
Log.v("EXAMPLE", "Updated custom user data document.");
} else {
Log.v("EXAMPLE", "Could not find custom user data document to update.");
}
} else {
Log.e("EXAMPLE", "Unable to insert custom user data. Error: " + result.getError());
}
});
} else {
Log.e("EXAMPLE", "Failed to log in anonymously:" + it.getError().toString());
}
});
// A user must be logged in to use a mongoClient
const user = app.currentUser;
const mongo = user.mongoClient("mongodb-atlas");
const collection = mongo.db("custom-user-data-database").collection("custom-user-data");
// Query for the user object of the logged in user
const filter = { userId: user.id};
// Set the logged in user's favorite color to pink
const update = { $set: { favoriteColor: "pink" }};
// Insert document if it doesn't already exist
const options = { upsert: true };
const result = await collection.updateOne(filter, update, options);
// Write the custom user data through a call
// to the `writeCustomUserData` function
val functionResponse = user.functions
.call<BsonDocument>("writeCustomUserData",
mapOf("userId" to user.id, "favoriteColor" to "blue")
)
// Refreshed custom user data contains updated
// `favoriteColor` value added in above Atlas Function call
user.refreshCustomData()
val updatedUserData = user.customDataAsBsonDocument()
val anonymousCredentials: Credentials = Credentials.anonymous()
app.loginAsync(anonymousCredentials) {
if (it.isSuccess) {
val user = app.currentUser()
val mongoClient : MongoClient =
user?.getMongoClient("mongodb-atlas")!! // service for MongoDB Atlas cluster containing custom user data
val mongoDatabase : MongoDatabase =
mongoClient.getDatabase("custom-user-data-database")!!
val mongoCollection : MongoCollection<Document> =
mongoDatabase.getCollection("custom-user-data-collection")!!
mongoCollection.updateOne(Document("user-id-field", user.id), Document("favoriteColor", "cerulean"))
.getAsync { result ->
if (result.isSuccess) {
if (result.get().modifiedCount == 1L) {
Log.v("EXAMPLE", "Updated custom user data document.")
} else {
Log.v("EXAMPLE", "Could not find custom user data document to update.")
}
} else {
Log.e("EXAMPLE", "Unable to update custom user data. Error: ${result.error}")
}
}
} else {
Log.e("EXAMPLE", "Failed to log in anonymously: ${it.error}")
}
}
RLMApp *app = [RLMApp appWithId:YOUR_APP_ID];
[app loginWithCredential:[RLMCredentials anonymousCredentials] completion:^(RLMUser *user, NSError *error) {
if (error != nil) {
NSLog(@"Failed to log in: %@", error);
return;
}
RLMMongoClient *client = [user mongoClientWithServiceName:@"mongodb-atlas"];
RLMMongoDatabase *database = [client databaseWithName:@"my_database"];
RLMMongoCollection *collection = [database collectionWithName:@"users"];
// Update the user's custom data document
[collection updateOneDocumentWhere:@{@"userId": [user identifier]}
updateDocument: @{@"favoriteColor": @"cerulean"}
completion:^(RLMUpdateResult *updateResult, NSError *error) {
if (error != nil) {
NSLog(@"Failed to insert: %@", error);
}
NSLog(@"Matched: %lu, modified: %lu", [updateResult matchedCount], [updateResult modifiedCount]);
}];
}];
let appId = YOUR_APP_SERVICES_APP_ID // replace this with your App ID
let app = App(id: appId)
app.login(credentials: Credentials.anonymous) { (result) in
switch result {
case .failure(let error):
print("Failed to log in: \(error.localizedDescription)")
case .success(let user):
// Access the custom user document remotely to update it.
let client = user.mongoClient("mongodb-atlas")
let database = client.database(named: "my_database")
let collection = database.collection(withName: "users")
collection.updateOneDocument(
filter: ["userId": AnyBSON(user.id)],
update: ["favoriteColor": "cerulean"]
) { (result) in
switch result {
case .failure(let error):
print("Failed to update: \(error.localizedDescription)")
return
case .success(let updateResult):
// User document updated.
print("Matched: \(updateResult.matchedCount), updated: \(updateResult.modifiedCount)")
}
}
}
}
// The documentation does not currently have this code example in TypeScript.
// Please refer to the other languages or related pages for example code.

Custom user data is stored in a document linked to the user object. Deleting a user does not delete the custom user data. To fully delete user data to comply with, for example, Apple's Account deletion guidance, you must manually delete the user's custom data document.

You can delete custom user data in a few ways:

  • Define a Function that you call to delete custom user data.

  • Access MongoDB through the SDK, if your language supports it, and delete the user data document from the custom user data collection directly.

  • Manually delete a custom data document through:

In this example, we use an Atlas Function to delete the custom user data document. The Atlas Function does not require any arguments. The Function uses the Function context to determine the caller's user ID, and deletes the custom user data document matching the user's ID.

deleteCustomUserData.js - Atlas Function running on server (JavaScript)
exports = async function deleteCustomUserData() {
const userId = context.user.id;
const customUserDataCollection = context.services
.get("mongodb-atlas")
.db("custom-user-data-database")
.collection("cpp-custom-user-data");
const filter = { userId };
const res = await customUserDataCollection.deleteOne(filter);
return res;
};

The code that calls this Function requires only a logged-in user to call the Function.

The following example uses MongoDB Data Access to find and deletes the data through the DeleteOneAsync() method.

This example calls an Atlas Function to delete custom user data. In this example, the Atlas Function does not require any arguments. The Function uses the function context to determine the caller's user ID, and deletes the custom user data document matching the user's ID.

deleteCustomUserData.js - Atlas Function running on server (JavaScript)
exports = async function deleteCustomUserData() {
const userId = context.user.id;
const customUserDataCollection = context.services
.get("mongodb-atlas")
.db("custom-user-data-database")
.collection("custom-user-data");
const filter = { userId };
const res = await customUserDataCollection.deleteOne(filter);
return res;
};

The SDK code that calls this function requires only a logged-in user to call the function.

auto deleteResult = user.call_function("deleteCustomUserData", "[]").get();
var deleteResult = await userDataCollection.DeleteOneAsync(
new BsonDocument("_id", user.Id));
// The `DeletedCount` should be 1
Console.WriteLine(deleteResult.DeletedCount);
// There should no longer be a custom user document for the user
var customData = await userDataCollection.FindOneAsync(
new BsonDocument("_id", user.Id));
Console.WriteLine(customData == null);
// The documentation does not currently have this code example in Dart.
// Please refer to the other languages or related pages for example code.
// The documentation does not have this code example in Java.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in JavaScript.
// Please refer to the other languages or related pages for example code.
val deleteResponse = user.functions
.call<BsonDocument>("deleteCustomUserData")
// The documentation does not have this code example in Kotlin for the Java SDK.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Objective-C.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in Swift.
// Please refer to the other languages or related pages for example code.
// The documentation does not currently have this code example in TypeScript.
// Please refer to the other languages or related pages for example code.

Back

Manage User Tokens

Next

User Metadata