Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Administrar usuarios

Datos de usuario personalizados - SDK de C++

Puedes leer el datos de usuario personalizados de un usuario actualmente conectado a través de ese usuario User Objeto. No se pueden editar datos de usuario personalizados mediante un User objeto. Para editar datos de usuario personalizados, consulte Actualizar datos de usuario personalizados. Para leer los datos, acceda a la custom_data propiedad del User objeto de un usuario conectado:

// 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");

Advertencia

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 C++ 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.

Nota

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.

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 the user's user ID.

Tip

En la interfaz de usuario de App Services, marque la casilla App Users página debajo de la pestaña Custom User Data para buscar y configurar ajustes de datos de usuario personalizados, incluidos:

  • The custom user data cluster, database, and collection

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

Una forma de crear este documento es llamando a una función Atlas que inserte un documento de datos personalizado en la colección de datos de usuario personalizada. No existe un patrón único para agregar datos de usuario personalizados desde una función Atlas. Debe escribir la función o funciones según el caso de uso de su aplicación.

In this example, 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.

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:

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();

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.

Puede actualizar datos de usuario personalizados utilizando una función Atlas, MongoDB Compass o MongoDB Atlas Data Explorer.

Para actualizar los datos de usuario personalizados de un usuario mediante una Atlas Function, edita el documento de MongoDB cuyo campo de ID de usuario contenga el ID del usuario. El siguiente ejemplo llama a la misma función utilizada para crear el documento de datos de usuario personalizado anterior. Aquí, actualizamos el campo favoriteColor del documento que contiene el ID de usuario del usuario actualmente autenticado:

// 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");

Tip

To determine a user's ID, access the user.identifier() property or find the user in the App Services UI on the App Users page under the Users tab.

Los datos de usuario personalizados se almacenan en un documento vinculado al objeto de usuario. Eliminar un usuario no elimina los datos de usuario personalizados. Para eliminar completamente los datos de usuario y cumplir, por ejemplo, con laguía de eliminación de cuentas de Apple., debe eliminar manualmente el documento de datos personalizados del usuario.

Puede eliminar datos de usuario personalizados utilizando una función Atlas, MongoDB Compass o MongoDB Atlas Data Explorer.

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("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:

auto deleteResult = user.call_function("deleteCustomUserData", "[]").get();

Volver

Administrar usuarios de correo electrónico y contraseña

En esta página