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

If object exists, upsert() behaves like Table.update().

If object doesn’t exist, upsert() behaves like Table.add().

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.

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 if object isn’t found.

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

Sample

db.friends.upsert(2, { name: 'Number 2' }).then((wasCreated) => {
  console.log(`Friend was ${wasCreated ? 'created' : 'updated'}`);
});
// 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'}`);
});

See Also

Table.update()

Table.put()

Collection.modify()

Table of Contents