Upserting Records with Remote Objects

Save a record by calling upsert() on a Remote Objects model instance.

upsert() is a convenience function that updates a record if it exists and creates it if it doesn’t. Behind the scenes upsert() delegates to create() or update(). Use upsert() to write functions for your page or application that aren’t affected by whether a record is from a new input form or an edit record page.

upsert() accepts two arguments, both optional.
RemoteObjectModel.upsert({field_values}, callback_function)
The field_values block enables you to set the values and save a record in one statement. Set field values as you do when you create a model, using a JSON string. For example, the following two calls to upsert() are equivalent.
// Call upsert() on a Contact model, with no arguments
// ct is a RemoteObjectModel.Contact that already has data
ct.set('Phone', '(415) 777-1212');
ct.upsert();

// Call upsert() on a Contact model, passing in field values
// ct is a RemoteObjectModel.Contact that already has data
ct.upsert({Phone: '(415) 777-1212'});

In the preceding example, it’s not clear if the contact exists in the database or if it’s a new contact that’s coming from an input form. upsert() handles the details. If there’s an Id field set on the contact, the contact will be updated. If there’s no Id, a new contact is created.

upsert() doesn’t return a result directly. The callback function enables you to handle the server response asynchronously.

All server operations that use Remote Objects are performed asynchronously. Any code that depends on the request being completed, including handling returned results, must be placed in the callback function.

Note

Your callback function can accept up to three arguments.
function callback(Error error, Array results, Object event) { // ... }
See Remote Objects Callback Functions for details about writing Remote Objects callback functions.