Table.upsert()

Since 4.2.1

Updates an existing object in the object store with the given changes, or creates a new object if it doesn’t exist

Syntax

table.upsert(key, changes);

Parameters

keyPrimary key
changesObject containing the key paths to each property you want to change.

Return Value

A Promise with a boolean: true if object was created or false if an existing object was updated.

Remarks

Similar to update() but with upsert behavior. The difference between upsert() and update() is that upsert() will create a new object if the key is not found, while update() will not change anything.

When creating a new object:

  • An empty object is created
  • The given changes are applied to this empty object
  • If the table has an inbound primary key, it will be set to the provided key value
  • The object is then inserted into the store

The difference between upsert() and put() is that upsert() will only apply the given changes to the object (or to a new empty object) while put() will replace the entire object.

Sample

db.friends.upsert(2, { name: 'Number 2', age: 25 }).then((wasCreated) => {
  console.log(`Friend was ${wasCreated ? 'created' : 'updated'}`);
});

With inbound primary key:

// If 'id' is the primary key and inbound
db.friends.upsert(2, { name: 'Number 2' }).then((wasCreated) => {
  // If friend with id=2 exists: updates name
  // If friend with id=2 doesn't exist: creates {id: 2, name: "Number 2"}
  console.log(`Friend was ${wasCreated ? 'created' : 'updated'}`);
});

Note: Be careful with nested object values. If you have an address field that includes city, state, and zipcode, then db.friends.upsert(2, {address: {zipcode: 12345}}) will replace the entire address object with {zipcode: 12345}. If you want to update the zipcode only, then use the dot notation as follows:

db.friends.upsert(friendId, {
  'address.zipcode': 12345
});

See Also

Table.update()

Table.put()

Collection.modify()

Table of Contents