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

Custom User Data - Flutter SDK

Puede almacenar datos personalizados arbitrarios sobre sus usuarios con Atlas App Services. Por ejemplo, puede almacenar el idioma preferido, la fecha de nacimiento o la zona horaria local de un usuario. Antes de escribir y leer estos datos, debe habilitar los datos de usuario personalizados en el backend. Para obtener más información, consulte Enable Custom User Data.

Importante

Currently you can only read custom user data with the Flutter SDK. In a future update to the SDK, you will be able to write custom user data from the SDK as well.

Puede crear, actualizar o eliminar datos de usuario personalizados utilizando uno de los otros SDK de Realm, con funciones de Atlas o consultando directamente a Atlas.

To use custom user data, you must first enable custom user data in App Services:

  1. Create an App.

  2. Enable custom user data.

Recupera datos de usuario personalizados en User.customData propiedad de un usuario conectado:

final customUserData = user.customData;

App Services no actualiza dinámicamente el valor de la User.customData Inmediatamente cuando cambian los datos subyacentes. En cambio, App Services obtiene la versión más reciente de los datos de usuario personalizados cada vez que un usuario actualiza su token de acceso o cuando se llama explícitamente a User.refreshCustomData(), lo que garantiza que la aplicación tenga los datos de usuario personalizados más recientes.

// refreshCustomData() returns the updated custom data object
final updatedCustomData = await user.refreshCustomData();
// Now when you access User.customData it's the value
// returned from User.refreshCustomData()

You can write to custom user data with an Atlas Function. Atlas Functions are server-side JavaScript functions that are built into your backend App. You can call an Atlas Function directly from the Realm Flutter SDK.

It is not possible to write to custom user data directly from the Realm Flutter SDK.

To learn more about Atlas Functions, refer to the following documentation:

There is no single pattern for adding custom user data from an Atlas Function. You should write your Function or Functions to suite your application's use case.

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.

writeCustomUserData.js - Atlas Function ejecutándose en el servidor (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;
};

El código del SDK de Realm para llamar a esta función:

Realm Flutter SDK client code (Dart)
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();

Volver

Vincular identidades de usuario

En esta página