快速入门 - Node.js SDK
在此页面上
此页面包含快速将 Realm 集成到您的应用程序中的信息。
如果尚未安装,请安装Realm Node.js SDK。
导入 Realm
在要使用Realm的源文件顶部,添加以下行以导入 SDK 和BSON库。
import Realm, { BSON } from "realm";
定义对象模型
应用程序的对象模型定义了可以在 Realm 中存储的数据。
要定义 Realm 对象类型,请创建一个指定该类型的 、 name
和properties
的模式对象。 在域中的Realm 对象类型中,类型名称必须是唯一的。有关如何定义特定属性的详细信息,请参阅“定义对象属性”。
以下代码展示了如何为Task
对象定义对象模型。 在此示例中:
是类型为 的
primaryKey
_id
int
。另一种常见的主键类型是ObjectId。name
字段为必填字段。status
和owner_id
字段为可选字段,紧邻数据类型之后用问号表示。
export class QuickstartTask extends Realm.Object { static schema = { name: "Task", properties: { _id: "objectId", name: "string", status: "string?", owner_id: "string?", }, primaryKey: "_id", }; }
export class QuickstartTask extends Realm.Object<Task> { _id!: BSON.ObjectID; name!: string; status?: string; owner_id?: string; static schema: ObjectSchema = { name: "Task", properties: { _id: "objectId", name: "string", status: "string?", owner_id: "string?", }, primaryKey: "_id", }; }
打开 Realm
要打开域,请将 Realm.BaseConfiguration对象传递给Realm.open()。
const realm = await Realm.open({ schema: [QuickstartTask], });
查找、排序和筛选对象
以下代码演示了如何:
查询“任务”对象类型的所有实例。
筛选查询以仅检索“未完成”的任务。
按名称升序对任务进行排序。
// Query for specific obect using primary key. const specificTask = realm.objectForPrimaryKey(QuickstartTask, testId); // Query realm for all instances of the "Task" type. const tasks = realm.objects(QuickstartTask); // Filter for all tasks with a status of "Open". const openTasks = tasks.filtered("status = 'Open'"); // Sort tasks by name in ascending order. const tasksByName = tasks.sorted("name");
创建、修改和删除 Realm 对象
打开 Realm 后,您可以在其中创建、修改和删除对象。 所有写入操作都必须在写事务中进行。
const allTasks = realm.objects(QuickstartTask); // Add a couple of Tasks in a single, atomic transaction. realm.write(() => { realm.create(QuickstartTask, { _id: firstId, name: "go grocery shopping", status: "Open", }); realm.create(QuickstartTask, { _id: secondId, name: "go exercise", status: "Open", }); }); const task1 = allTasks.find( (task) => task._id.toString() == firstId.toString() ); const task2 = allTasks.find( (task) => task._id.toString() == secondId.toString() ); realm.write(() => { // Modify an object. task1!.status = "InProgress"; // Delete an object. realm.delete(task2!); });
观看集合
您可以通过 Realm.addListener() 注册事件处理程序来监视 Realm 、集合或对象的更改 。Object.addListener() Collection.addListener()方法。
重要
顺序很重要
在集合通知处理程序中,始终按以下顺序应用变更:删除、插入和修改。在删除操作之前处理插入操作可能会导致意外行为。
在以下示例中,应用程序开发者监视对Task
集合的更改。
// Define the collection notification listener. const listener = (tasks, changes) => { // Update UI in response to deleted objects. changes.deletions.forEach((index) => { // Deleted objects cannot be accessed directly, // but we can update a UI list, etc. knowing the index. console.log(`A task was deleted at the ${index} index.`); // ... }); // Update UI in response to inserted objects. changes.insertions.forEach((index) => { const insertedTasks = tasks[index]; console.log(`insertedTasks: ${JSON.stringify(insertedTasks, null, 2)}`); // ... }); // Update UI in response to modified objects. // `newModifications` contains an index to the modified object's position // in the collection after all deletions and insertions have been applied. changes.newModifications.forEach((index) => { const modifiedTask = tasks[index]; console.log(`modifiedTask: ${JSON.stringify(modifiedTask, null, 2)}`); // ... }); }; // Observe collection notifications. tasks.addListener(listener);
// Define the collection notification listener. //@ts-expect-error TYPEBUG: OrderedCollection is incorrectly implemented const listener: Realm.CollectionChangeCallback = ( tasks: Realm.OrderedCollection<QuickstartTask>, changes: Realm.CollectionChangeSet ) => { // Update UI in response to deleted objects. changes.deletions.forEach((index) => { // Deleted objects cannot be accessed directly, // but we can update a UI list, etc. knowing the index. console.log(`A task was deleted at the ${index} index.`); // ... }); // Update UI in response to inserted objects. changes.insertions.forEach((index) => { const insertedTasks = tasks[index]; console.log(`insertedTasks: ${JSON.stringify(insertedTasks, null, 2)}`); // ... }); // Update UI in response to modified objects. // `newModifications` contains an index to the modified object's position // in the collection after all deletions and insertions have been applied. changes.newModifications.forEach((index) => { const modifiedTask = tasks[index]; console.log(`modifiedTask: ${JSON.stringify(modifiedTask, null, 2)}`); // ... }); }; // Observe collection notifications. //@ts-expect-error TYPEBUG: OrderedCollection is incorrectly implemented tasks.addListener(listener);
关闭 Realm
调用realm.close() 方法,以避免内存泄漏。
// Close the realm. realm.close();
添加 Device Sync(可选)
本节说明如何使用匿名用户进行身份验证,并打开 Flexible Sync Realm 以在设备之间同步数据。
先决条件
在 用户界面中启用 匿名身份验证Atlas App Services
在 开发模式 开启且 部分中有 字段的情况下启用了 Flexible Sync
owner_id
Queryable Fields
初始化 App Services
要使用Atlas App Services 功能,例如身份验证和同步,您必须首先使用App Services App App 访问您的ID 。您可以在 用户界面中 找到您的 AppID Atlas App Services。
// Initialize your App. const app = new Realm.App({ id: "<yourAppId>", });
验证用户身份
要对用户进行身份验证并登录,请调用App.logIn() 。 启用匿名身份验证后,用户无需提供任何身份信息即可立即登录您的应用:
// Initialize your App. const app = new Realm.App({ id: "<yourAppId>", }); // Authenticate an anonymous user. const anonymousUser = await app.logIn(Realm.Credentials.anonymous());
定义对象模型
同步 Realm 的对象模型的工作方式与仅限本地 Realm相同。 就像定义仅限本地的 Realm 一样定义对象模型。
export class QuickstartTask extends Realm.Object { static schema = { name: "Task", properties: { _id: "objectId", name: "string", status: "string?", owner_id: "string?", }, primaryKey: "_id", }; }
export class QuickstartTask extends Realm.Object<Task> { _id!: BSON.ObjectID; name!: string; status?: string; owner_id?: string; static schema: ObjectSchema = { name: "Task", properties: { _id: "objectId", name: "string", status: "string?", owner_id: "string?", }, primaryKey: "_id", }; }
打开同步 Realm
初始化应用、验证用户身份并定义对象模型后,您可以创建SyncConfiguration。
要打开 Flexible Sync Realm,请调用Realm.open() 。 传入 BaseConfiguration对象,该对象必须包含定义SyncConfiguration对象的sync
属性。 要使用 Flexible Sync,必须在 SyncConfiguration 中包含user
和flexible: true
。
此外,您至少需要一个订阅,然后才能读取或写入 Realm。 使用Configuration.sync.initialSubscriptions
定义首次打开 Realm 文件时的初始订阅集。
// Initialize your App. const app = new Realm.App({ id: "<yourAppId>", }); // Authenticate an anonymous user. const anonymousUser = await app.logIn(Realm.Credentials.anonymous()); // Create a `SyncConfiguration` object. const config = { schema: [QuickstartTask], sync: { // Use the previously-authenticated anonymous user. user: anonymousUser, // Set flexible sync to true to enable sync. flexible: true, // Define initial subscriptions to start syncing data as soon as the // realm is opened. initialSubscriptions: { update: (subs, realm) => { subs.add( // Get objects that match your object model, then filter them by // the `owner_id` queryable field realm .objects(QuickstartTask) .filtered(`owner_id == "${anonymousUser.id}"`) ); }, }, }, }; const realm = await Realm.open(config);
// Initialize your App. const app = new Realm.App({ id: "<yourAppId>", }); // Authenticate an anonymous user. const anonymousUser = await app.logIn(Realm.Credentials.anonymous()); // Create a `SyncConfiguration` object. const config: Realm.Configuration = { schema: [QuickstartTask], sync: { // Use the previously-authenticated anonymous user. user: anonymousUser, // Set flexible sync to true to enable sync. flexible: true, // Define initial subscriptions to start syncing data as soon as the // realm is opened. initialSubscriptions: { update: (subs, realm) => { subs.add( // Get objects that match your object model, then filter them by // the `owner_id` queryable field realm .objects(QuickstartTask) .filtered(`owner_id == "${anonymousUser.id}"`) ); }, }, }, }; const realm = await Realm.open(config);
在同步 Realm 上读取、写入和监控变更的语法与对上述非同步 Realm 的语法相同。当您使用本地数据时,后台线程可以高效地集成、上传和下载变更集。