.update()

Updates the entries that match the provided filter with the provided callback. Updates all the entries if no filter is provided.

update(updateCallback, filter)

// Note: People is a collection.

People.get();  // [{ id: 1, name: 'Peter', salary: 1200 }, { id: 2, name: 'Michael', salary: 900 }] 

// Updating a value from all matching entries
People.update(
  person => person.salary += 100,
  target => target.salary < 1000
); // [{ id: 2, name: 'Michael', salary: 1000 }] 

// Deleting the 'name' key from all matching entries
People.update(
  person => person.name = undefined,
  target => target.salary === 1000
); // [{ id: 2, salary: 1000 }]

// Updating all entries (by omitting the filter)
People.update(person => person.salary += 500); // [{ id: 1, name: 'Peter', salary: 1700 }, { id: 2, salary: 1500 }] 

// Updating multiple values from all entries (by omitting the filter)
People.update(
  person => {
    if (!person.name) person.name = 'John';
  
    if (person.id === 1)
      person.salary += 300;
    else
      person.salary += 150;
      
    person.isChief = person.id === 1;
  }
); // [{ id: 1, name: 'Peter', salary: 2000, isChief: true } , { id: 2, name: 'John', salary: 1650, isChief: false }] 

A new way of updating an entry's data from a collection was introduced in version 2.11.0.

Now, instead of using the Collection#update method, you can simply get or fetch the entry's data with Collection#get, Collection#fetch, Collection#getOrCreate or Collection#fetchOrCreate, update a property directly in the code and then use the new Data#save method.

See the examples below:

const user = Users.get(u => u.name === 'Peter');

user.age = 20;
user.save();

Last updated