Overview
カスタム ユーザー データと呼ばれる、アプリケーション ユーザーに関する任意のデータを、ウェブ アプリケーション内で直接読み取ることができます。 たとえば、ユーザーの希望言語、誕生日、ローカル タイムゾーン を保存できます。
Realm はリンクされたクラスター内の MongoDB コレクションを参照して特定のユーザーのカスタム データを検索しますが、カスタム ユーザー データ ドキュメントの追加や更新は行われません。 コレクション内のユーザー データの管理と更新は、ユーザーによって管理されます。 カスタム ユーザー データの有効化と構成方法の詳細については、 カスタム ユーザー データの有効化 を参照してください。
ユーザー オブジェクトの例
このページのコード例では、 custom_data
フィールドがまだ設定されていない次のユーザー オブジェクトを使用します。
{ id: '5f1f216e82df4a7979f9da93', type: 'normal', data: { email: 'test@example.com' }, custom_data: { _id: '5f20d083a37057d55edbdd57', userID: '5f1f216e82df4a7979f9da93', description: 'a test document for user: test@example.com', }, identities: [ { id: '5f1f216e82df4a7979f9da90', provider_type: 'local-userpass' } ] }
重要
カスタム ユーザー データを使用するには、まずカスタム ユーザー データを有効にする 必要があります。
カスタムユーザーデータの読み取り
警告
カスタム データは古い可能性があります
App Services は、基礎となるドキュメントが変更された場合にユーザーのカスタム データを動的に更新しません。 代わりに、ユーザーがログインする時などアクセス トークンを更新するたびに、App Services はデータの新しいコピーを取得します。 これは変更をすぐに反映しないことを意味する可能性があります。 認証triggerからの更新 トークンが更新されない場合、SDK は 30 分待機した後、バックエンドへの次回の呼び出しで更新するため、カスタム ユーザー データは最大 30 分間、およびバックエンドへの次回の SDK 呼び出しが発生するまでの時間によって古くなる可能性があります。
ログイン ユーザーのカスタム データの読み取り専用コピーには、 Realm.User.customDataプロパティから直接アクセスできます。
// Access a logged in user's read-only custom data const customData = app.currentUser.customData;
ユーザーのカスタム データの最新バージョンを手動で取得するには、 User.refreshCustomData() を呼び出します。
// Refresh a user's custom data to make sure we have the latest version await app.currentUser.refreshCustomData();
出力
{ "_id": "5f233a3ac49aca916792de1d", "description": "a test document for user test@example.com", "userID": "5f1f298f757611faec901d0f", "favoriteColor": "pink" }
ユーザーのカスタム データの変更
注意
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. アプリケーションからカスタム データへのクライアントの書込みアクセスを制限する場合は、システム関数からオブジェクトを変更できます。
ユーザーのカスタム データを変更するには、アプリのカスタム データ コレクション内の基礎となるドキュメントを更新します。
次の例では、ユーザーのカスタム データをアップデートして、 favoriteColor
プロパティを"purple"
に設定します。
// Get a client object for your app's custom user data collection const mongo = app.currentUser.mongoClient(CLUSTER_NAME); const collection = mongo.db(DATABASE_NAME).collection(COLLECTION_NAME); // Log the user's favorite color before we change it console.log( "old favoriteColor: ", app.currentUser.customData.favoriteColor ); // Update the user's custom data document await collection.updateOne( { userId: app.currentUser.id }, // Query for the user object of the logged in user { $set: { favoriteColor: "purple" } } // Set the logged in user's favorite color to purple ); // Refresh the user's local customData property await app.currentUser.refreshCustomData(); // Log the user's new favorite color console.log( "new favoriteColor: ", app.currentUser.customData.favoriteColor );
出力
old favoriteColor: pink new favoriteColor: purple
概要
カスタム ユーザー データを使用して、アプリケーション ユーザーに関する情報を保存できます。
ユーザーオブジェクトのカスタムユーザーデータフィールドは読み取り専用であり、Atlas サービスを通じて CRUD 操作を実行することによってのみ に変更できます。