Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ /
Atlas Device SDK
/ /

CRUD - Update - Node.js SDK

書込みトランザクション内で他の JavaScript オブジェクトをアップデートするのと同じ方法で、Realm オブジェクトのプロパティを追加、変更、または削除できます。

// Open a transaction.
realm.write(() => {
// Get a dog to update.
const dog = realm.objects("Dog")[0];
// Update some properties on the instance.
// These changes are saved to the realm.
dog.name = "Maximilian";
dog.age += 1;
});

Tip

関連オブジェクトと埋め込みオブジェクトの更新

To update a property of an embedded object or a related object, modify the property with dot-notation or bracket-notation as if it were in a regular, nested object.

オブジェクトをアップサートするには、更新モードを modifiedに設定してRealm.create()を呼び出します。 この操作では、指定されたプライマリキーを持つ新しいオブジェクトを挿入するか、そのプライマリキーをすでに持っている既存のオブジェクトを更新します。

realm.write(() => {
// Add a new person to the realm. Since nobody with ID 1234
// has been added yet, this adds the instance to the realm.
person = realm.create(
"Person",
{ _id: 1234, name: "Joe", age: 40 },
"modified"
);
// If an object exists, setting the third parameter (`updateMode`) to
// "modified" only updates properties that have changed, resulting in
// faster operations.
person = realm.create(
"Person",
{ _id: 1234, name: "Joseph", age: 40 },
"modified"
);
});

To apply an update to a collection of objects, iterate through the collection (e.g. with for...of). In the loop, update each object individually:

realm.write(() => {
// Create someone to take care of some dogs.
const person = realm.create("Person", { name: "Ali" });
// Find dogs younger than 2.
const puppies = realm.objects("Dog").filtered("age < 2");
// Loop through to update.
for (const puppy of puppies) {
// Give all puppies to Ali.
puppy.owner = person;
}
});

注意

逆の関係

Dog.ownerからPerson.dogsへの逆関係の結果、Realm は、子をパーティションの所有者として設定するたびに、エイリアスの犬のリストを自動的に更新します。

戻る

読み取り

項目一覧