CRUD - 更新 - Node.js SDK
Atlas Device SDK 已弃用。 有关详细信息,请参阅弃用页面。
更新对象
您可以在写事务(write transaction)中添加、修改或删除 Realm 对象的属性,就像更新任何其他 JavaScript 对象一样。
// 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; });
更新或插入(upsert)对象
要更新或插入对象,请调用Realm.create()并将更新模式设置为 modified
。 该操作要么插入具有给定主键的新对象,要么更新已具有该主键的现有对象。
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" ); });
批量更新集合
要将更新应用于对象集合,请遍历该集合(例如,使用 for...of )。在循环中,单独更新每个对象:
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; } });