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 - Java SDK

Puede leer datos arbitrarios sobre los usuarios de su aplicación, conocidos como datos de usuario personalizados, directamente en su aplicación Java. Por ejemplo, puede almacenar el idioma preferido, la fecha de nacimiento o la zona horaria local de un usuario. Para obtener más información sobre los datos de usuario personalizados, consulte Enable Custom User Data.

Importante

Para utilizar datos de usuario personalizados, primero debe habilitar datos de usuario personalizados.

Puede leer los datos de usuario personalizados de un usuario que haya iniciado sesión actualmente a través del perfil 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 acceder a los datos, llame al método User.customData() en el User objeto de un usuario conectado:

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

Advertencia

Custom Data May Be Stale

Atlas App Services does not dynamically update the value of User.customData() 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 occurs during most SDK operations that contact the App Services back end. Realm refreshes access tokens every 30 minutes, so custom user data can be stale for no more than 30 minutes.

Si necesitas la versión más reciente de los datos de usuario personalizados, utiliza el User.refreshCustomData() método para solicitar la versión más actualizada de los datos personalizados de un usuario.

Tip

To create, update, or delete custom user data, you will need the following information from your custom user data configuration:

  • el clúster de datos de usuario personalizado

  • la base de datos de usuario personalizada

  • the custom user data collection in which custom user data documents are stored

  • the user ID field used to map custom user data documents to users (via user ID)

Puede encontrar esta información en la interfaz de usuario de App Services en la App Users página bajo la pestaña Custom User 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. 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:

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

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 update custom user data using MongoDB Data Access, Realm Sync, MongoDB Compass, or the MongoDB Atlas Data Explorer.

Para actualizar los datos de usuario personalizados de un usuario con MongoDB Data Access, edite el documento MongoDB cuyo campo de ID de usuario contiene el ID de usuario del usuario.

Tip

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

El siguiente ejemplo utiliza MongoDB Data Access para actualizar el favoriteColor campo del documento que contiene el ID de usuario del usuario actualmente conectado en la colección de datos de usuario personalizada:

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

Volver

Authenticate Users

En esta página