CodeAPI

wix-data

The wix-data module contains functionality for working with data in collections.

To use the data module, import wixData from the wix-data module:

   import wixData from 'wix-data';

The wix-data API can be used in your site’s front-end or backend code.

The wix-data API includes fuctions for managing the data in your collections, building queries on collections, and registering hooks.

For more information, see Working with the Data API.

Data Types

The following is a list of the field types from database collections and their corresponding JavaScript data types. When you retrieve data from a collection, that data will be represented in the JavaScript data types that correspond to your collection's field types. When you add or update data in a collection, you provide the data using the JavaScript data types that correspond to your collection's field types.

Field TypeData TypeNotes
TextJavaScript string
ImageJavaScript stringAn image URL as described here.
BooleanJavaScript boolean
NumberJavaScript number
Date and TimeJavaScript Date object
Rich TextJavaScript stringA string which can contain a subset of HTML tags.
URLJavaScript stringA valid URL.
DocumentJavaScript stringA Media Manager document URL as described here.
VideoJavaScript stringA video URL as described here.
ReferenceJavaScript stringAn item ID from the referenced collection.
Media GalleryJavaScript arrayEach element in the array is either an ImageItem or VideoItem.

Table of Contents

FUNCTIONS

?
Perform actions on an object.
aggregate( )Creates an aggregation.
filter( )Creates a filter to be used with the dataset setFilter() function.
get( )Retrieves an item from a collection.
insert( )Adds an item to a collection.
insertReference( )Inserts a reference in the specified property.
isReferenced( )

Checks if a reference to the referenced item exists in the specified property of the referring item.

query( )Creates a query.
queryReferenced( )Gets the full items referenced in the specified property.
remove( )Removes an item from a collection.
removeReference( )Removes a reference from the specified property.
replaceReferences( )Replaces current references with references in the specified property.
save( )Inserts or updates an item in a collection.
sort( )Creates a sort to be used with the dataset setSort() function.
update( )Updates an item in a collection.

OBJECTS

?
Objects used when setting, getting, or calling the properties and methods listed above.
WixDataOptionsAn object that you pass as the options parameter that modifies how an operation is performed.
WixDataQueryReferencedOptionsAn object for controlling the order of returned referenced items.

aggregate( )

Creates an aggregation.

Description

The aggregate() function builds an aggregation on the specified collection and returns a WixDataAggregate object.

The returned object contains the aggregate definition which is typically used to run the aggregation using the run() function.

You can refine the aggregation by chaining WixDataAggregate functions on to the aggregate.

The aggregate() function runs with the following WixDataAggregate defaults that you can override:

Syntax

function aggregate(collectionName: string): WixDataAggregate
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The collection to run the aggregation on.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
An aggregate object.

Examples

Perform an aggregation

aggregate.run()
  .then( (results) => {
    let items = results.items;
    let numItems = results.length;
    let hasNext = results.hasNext();
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );

Create an aggregation and run it

import wixData from 'wix-data';

// ...

const filter = wixData.filter().eq("year", 2010);
const having = wixData.filter().gt("maxPopulation", 1000000);

wixData.aggregate("PopulationData")
  .filter(filter)
  .group("state")
  .max("population", "maxPopulation")
  .having(having)
  .descending("maxPopulation")
  .skip(5)
  .limit(3)
  .run()
  .then( (results) => {
    let items = results.items;
    let numItems = results.length;
    let hasNext = results.hasNext();
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );

filter( )

Creates a filter to be used with the dataset setFilter() function.

Description

This function is not used on its own. It is only used to create a filter for a dataset using the setFilter() function.

Syntax

function filter(): WixDataFilter
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
A filter object.

Examples

Filter a dataset

import wixData from 'wix-data';

// ...

$w("#myDataset").setFilter( wixData.filter()
  .startsWith("lastName", "D")
  .ge("age", "21")
);

get( )

Retrieves an item from a collection.

Description

The get() function returns a Promise that resolves to the item with ID itemId from the specified collection. The Promise is rejected if the current user does not have read permissions for the collection.

Calling the get() function triggers the beforeGet() and afterGet() hooks if they have been defined.

Use the options parameter to run get() without checking for permissions or without its registered hooks.

Syntax

function get(collectionName: string, itemId: string, [options: WixDataOptions]): Promise<Object>
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The name of the collection to retrieve the item from.
itemId
string
The ID of the item to retrieve.
options(Optional)
An object with one or both of the following boolean properties: suppressAuth, suppressHooks.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Object>

Fulfilled - The retrieved item. Rejected - The error that caused the rejection.

Examples

Get an item from a collection

import wixData from 'wix-data';

// ...

wixData.get("myCollection", "00001")
  .then( (results) => {
    let item = results; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  item is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Get an item from a collection using data options

import wixData from 'wix-data';

// ...

let options = {
  "suppressAuth": true,
  "suppressHooks": true
};

wixData.get("myCollection", "00001", options)
  .then( (results) => {
    let item = results; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  item is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

insert( )

Adds an item to a collection.

Description

The insert() function returns a Promise that resolves to the inserted item after it has been added to the specified collection. The Promise is rejected if the current user does not have create permissions for the collection or the specified item includes an _id property whose value matches an existing ID in the collection. Meaning, insert() cannot overwrite an existing item in the collection.

Calling the insert() function triggers the beforeInsert() and afterInsert() hooks if they have been defined.

Use the options parameter to run insert() without checking for permissions or without its registered hooks.

When inserting an item into a collection that has a reference field, set the value of the reference field to the referenced item's _id value or the entire referenced item object.

The insert() function adds the following properties and values to the item when it adds it to the collection:

  • _id: A unique identifier for the item with collection, if the item does not include one. You can optionally provide your own ID. Once an ID is assigned to an item it cannot be changed.
  • _createdDate: The date the item was added to the collection.
  • _updatedDate: The date the item was modified. When the item is first added, the createdDate and updatedDate are the same.

Any valid JavaScript object can be added as a property value. The insert() function maintains the structure of the specified object. For example, objects that contain nested objects, Arrays, or Arrays with nested objects are all added to the collection as defined.

The maximum size of an item that you can add to a collection is 200kb.

Syntax

function insert(collectionName: string, item: Object, [options: WixDataOptions]): Promise<Object>
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The name of the collection to add the item to.
item
Object
The item to add.
options(Optional)
An object with one or both of the following boolean properties: suppressAuth, suppressHooks.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Object>

Fulfilled - The item that was added. Rejected - The error that caused the rejection.

Examples

Insert an item into a collection

import wixData from 'wix-data';

// ...

let toInsert = {
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe"
};

wixData.insert("myCollection", toInsert)
  .then( (results) => {
		let item = results; //see item below
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

/*  item is:
 *
 *  {
 *    "_id":          "rifk4nrk-dj4o-djhe-oidk-fnoqw4oiglk4i",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Insert an item with a specified ID into a collection

import wixData from 'wix-data';

// ...

let toInsert = {
  "_id":          "00001",
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe"
};

wixData.insert("myCollection", toInsert)
  .then( (results) => {
		let item = results; //see item below
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

/*  item is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Insert an item into a collection using data options

import wixData from 'wix-data';

// ...

let toInsert = {
  "_id":          "00001",
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe"
};

let options = {
  "suppressAuth": true,
  "suppressHooks": true
};

wixData.insert("myCollection", toInsert, options)
  .then( (results) => {
		let item = results; //see item below
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

/*  item is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Insert an item including a reference to another item using the referenced item's ID

import wixData from 'wix-data';

// ...

let countryId = "id-of-usa-item";

let toInsert = {
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe",
  "country":      countryId
};

wixData.insert("myCollection", toInsert)
  .then( (results) => {
    let item = results; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  item is:
 *
 *  {
 *    "_id":          "rifk4nrk-dj4o-djhe-oidk-fnoqw4oiglk4i",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe",
 *    "country":      "id-of-usa-item"
 *  }
 */

Insert an item including a reference to another item using the reference item

import wixData from 'wix-data';

// ...

let countryItem = // get country item from somewhere

let toInsert = {
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe",
  "country":      countryItem
};

wixData.insert("myCollection", toInsert)
  .then( (results) => {
    let item = results; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  item is:
 *
 *  {
 *    "_id":          "rifk4nrk-dj4o-djhe-oidk-fnoqw4oiglk4i",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe",
 *    "country":      "id-of-usa-item"
 *  }
 */

insertReference( )

Inserts a reference in the specified property.

Description

The insertReference() function returns a Promise that resolves when a reference to the referenced item(s) is added to the referring item in the specified property. The Promise is rejected if the current user does not have update permissions for the collection.

Calling the insertReference() function does not trigger any hooks.

Syntax

function insertReference(collectionName: string, propertyName: string, referringItem: Object | string, referencedItem: Object | string | Array<Object> | Array<string>, [options: WixDataOptions]): Promise<void>
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The name of the collection that contains the referring item.
propertyName
string
The property to insert the reference into.
referringItem
Object | string
The referring item or referring item's ID.
referencedItem
Object | string | Array<Object> | Array<string>
The referenced item, referenced item's ID, an array of referenced items, or an array of referenced item IDs.
options(Optional)
An object with one or both of the following boolean properties: suppressAuth, suppressHooks.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>

Fulfilled - When the references have been inserted. Rejected - The error that caused the rejection.

Examples

Insert a reference

This example inserts a reference to the item with ID 12345 in the actors field of the item in the movies collection with the ID 00001.

import wixData from 'wix-data';

// ...

wixData.insertReference("movies", "actors", "00001", "12345")
  .then( () => {
    console.log("Reference inserted");
  } )
  .catch( (error) => {
    console.log(error);
  } );

Insert references using an array

This example inserts a reference to the items with IDs 12345 and 67890 in the actors field of the item in the movies collection with the ID 00001.

import wixData from 'wix-data';

// ...

wixData.insertReference("movies", "actors", "00001", ["12345", "67890"])
  .then( () => {
    console.log("Reference inserted");
  } )
  .catch( (error) => {
    console.log(error);
  } );

isReferenced( )

Checks if a reference to the referenced item exists in the specified property of the referring item.

Description

The isReferenced() function returns a Promise that resolves to true if the referring item contains a reference to the referenced item in the specified property. The Promise is rejected if the current user does not have read permissions for the collection.

Calling the queryReferenced() function does not trigger any hooks.

Syntax

function isReferenced(collectionName: string, propertyName: string, referringItem: Object | string, referencedItem: Object | string): Promise<boolean>
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The name of the collection that contains the referring item.
propertyName
string
The property that possibly contains the references to the referenced item.
referringItem
Object | string
The referring item or referring item's ID.
referencedItem
Object | string
The referenced item or referenced item's ID.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<boolean>

Fulfilled - Whether the referring item contains a reference to the referenced item or not. Rejected - The error that caused the rejection.

Examples

Get referenced items

This example checks if the item in the Movies collection with the ID 00001 has a reference in its actors field that refers to an item with the ID 12345.

import wixData from 'wix-data';

// ...

wixData.isReferenced("movies", "actors", "00001", "12345")
  .then( (result) => {
    let isReferenced = result;  // true
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

query( )

Creates a query.

Description

The query() function builds a query on the specified collection and returns a WixDataQuery object.

The returned object contains the query definition which is typically used to run the query using the find() function.

You can refine the query by chaining WixDataQuery functions on to the query. WixDataQuery functions enable you to sort, filter, and control the number of results a query returns.

The query() runs with the following WixDataQuery defaults that you can override:

The functions that are chained to query() are applied in the order they are called. For example, if you sort on an age property in ascending order and then on a name property in descending order, the results are sorted first by the age of the items and then, if there are multiple results with the same age, the items are sorted by name in descending order, per age value.

Syntax

function query(collectionName: string): WixDataQuery
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The collection to run the query on.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
A query object.

Examples

Build a query

import wixData from 'wix-data';

// ...

let query = wixData.query("myCollection");

Build and perform a query

import wixData from 'wix-data';

// ...

wixData.query("myCollection")
  .find()
  .then( (results) => {
    let firstItem = results.items[0]; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  firstItem is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Build and perform a query using data options

import wixData from 'wix-data';

// ...

wixData.query("myCollection")
  .eq("title", "Dr.")
  .find()
  .then( (results) => {
    let firstItem = results.items[0]; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  firstItem is:
 *
 *  {
 *    "_id":          "00002",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Dr.",
 *    "first_name":   "Jane",
 *    "last_name":    "Doe"
 *  }
 */

Build a query incrementally

This example builds a query based on certain conditions. It then performs the query and uses the results to populate a table.

import wixData from 'wix-data';

// ...

function runQuery(low, high) {
  let query = wixData.query("myCollection");

  if(low) {
    query = query.ge("price", low);
  }

  if(high) {
    query = query.le("length", high);
  }

  query.find()
    .then( (results) => {
      $w("#myTable").rows = results.items;
    } );
}

queryReferenced( )

Gets the full items referenced in the specified property.

Description

The queryReferenced() function returns a Promise that resolves to the full items that are referenced in the specified property of the item from the specified collection. The Promise is rejected if the current user does not have read permissions for the specified collection or the collection containing the referenced items.

For example, suppose you have a movies collection with an actors field that contains references to items in a people collection. Querying the movies collection using queryReferenced() returns the relevant people items referenced in the actors field of the specified movies item. Meaning, it returns the full actor information for all actors in the specified movie.

The queryReferenced() function can be used instead of a standard query() with an include() to overcome the limitations of the include() function.

You can optionally control the order of the returned referenced items by passing a WixDataQueryReferencedOptions object.

Calling the queryReferenced() function does not trigger any hooks.

Syntax

function queryReferenced(collectionName: string, item: Object | string, propertyName: string, options: WixDataQueryReferencedOptions): Promise<Array<Object>>
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The name of the collection that contains the referring item.
item
Object | string
The referring item or referring item's ID.
propertyName
string
The property that contains the references to the referenced items.
options
An object for controlling the order of the returned referenced items.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Array<Object>>

Fulfilled - The referenced items. Rejected - The error that caused the rejection.

Examples

Get referenced items

This example finds the item in the Movies collection with the ID 00001. It gets all of the items referenced in the actors field of that item and then stores the first actor in a variable.

import wixData from 'wix-data';

// ...

wixData.queryReferenced("movies", "00001", "actors")
  .then( (results) => {
    let firstItem = results.items[0]; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  firstItem is:
 *
 *  {
 *    "_id":          "12345",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Get referenced items using options

import wixData from 'wix-data';

// ...

let options = {
  "order": "asc"
};

wixData.queryReferenced("movies", "00001", "actors", options)
  .then( (results) => {
    let firstItem = results.items[0]; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  firstItem is:
 *
 *  {
 *    "_id":          "12345",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

remove( )

Removes an item from a collection.

Description

The remove() function returns a Promise that resolves to the removed item after the it has been removed from the specified collection. The Promise is rejected if the current user does not have delete permissions for the collection.

Calling the remove() function triggers the beforeRemove() and afterRemove() hooks if they have been defined.

Use the options parameter to run remove() without checking for permissions or without its registered hooks.

Syntax

function remove(collectionName: string, itemId: string, [options: WixDataOptions]): Promise<Object>
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The collection to remove the item from.
itemId
string
The ID of the item to remove.
options(Optional)
An object with one or both of the following boolean properties: suppressAuth, suppressHooks.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Object>

Fulfilled - The removed item. Rejected - The error that caused the rejection.

Examples

Remove an item from a collection

import wixData from 'wix-data';

// ...

wixData.remove("myCollection", "00001")
  .then( (results) => {
    let item = results; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  item is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Remove an item from a collection using data options

import wixData from 'wix-data';

// ...

let options = {
  "suppressAuth": true,
  "suppressHooks": true
};

wixData.remove("myCollection", "00001", options)
  .then( (results) => {
    let item = results; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  item is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

removeReference( )

Removes a reference from the specified property.

Description

The removeReference() function returns a Promise that resolves when a reference to the referenced item(s) is removed from the specified property in the referring item. The Promise is rejected if the current user does not have update permissions for the collection.

Calling the removeReference() function does not trigger any hooks.

Syntax

function removeReference(collectionName: string, propertyName: string, referringItem: Object | string, referencedItem: Object | string | Array<Object> | Array<string>, [options: WixDataOptions]): Promise<void>
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The name of the collection that contains the referring item.
propertyName
string
The property to insert the reference into.
referringItem
Object | string
The referring item or referring item's ID.
referencedItem
Object | string | Array<Object> | Array<string>
The referenced item, referenced item's ID, an array of referenced items, or an array of referenced item IDs.
options(Optional)
An object with one or both of the following boolean properties: suppressAuth, suppressHooks.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>

Fulfilled - When the references have been removed. Rejected - The error that caused the rejection.

Examples

Remove a reference

This example removes a reference to the item with ID 12345 from the actors field of the item in the movies collection with the ID 00001.

import wixData from 'wix-data';

// ...

wixData.removeReference("movies", "actors", "00001", "12345")
  .then( () => {
    console.log("Reference inserted");
  } )
  .catch( (error) => {
    console.log(error);
  } );

Remove references using an array

This example removes a reference to the items with IDs 12345 and 67890 from the actors field of the item in the movies collection with the ID 00001.

import wixData from 'wix-data';

// ...

wixData.removeReference("movies", "actors", "00001", ["12345", "67890"])
  .then( () => {
    console.log("Reference inserted");
  } )
  .catch( (error) => {
    console.log(error);
  } );

replaceReferences( )

Replaces current references with references in the specified property.

Description

The replaceReferences() function returns a Promise that resolves when the item's current references in the specified property are removed and references to the referenced items are added in their place. The Promise is rejected if the current user does not have update permissions for the collection.

Calling the replaceReferences() function does not trigger any hooks.

Syntax

function replaceReferences(collectionName: string, propertyName: string, referringItem: Object | string, referencedItem: Object | string | Array<Object> | Array<string>, [options: WixDataOptions]): Promise<void>
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The name of the collection that contains the referring item.
propertyName
string
The property to replaces the references in.
referringItem
Object | string
The referring item or referring item's ID.
referencedItem
Object | string | Array<Object> | Array<string>
The referenced item, referenced item's ID, an array of referenced items, or an array of referenced item IDs.
options(Optional)
An object with one or both of the following boolean properties: suppressAuth, suppressHooks.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>

Fulfilled - When the references have been inserted. Rejected - The error that caused the rejection.

Examples

Replace a reference

This example replaces the references in the actors field of the item in the movies collection with the ID 00001 with a reference to the item with ID 12345.

import wixData from 'wix-data';

// ...

wixData.replaceReferences("movies", "actors", "00001", "12345")
  .then( () => {
    console.log("References replaced");
  } )
  .catch( (error) => {
    console.log(error);
  } );

Replace references using an array

This example replaces the references in the actors field of the item in the movies collection with the ID 00001 with references to the items with IDs 12345 and 67890.

import wixData from 'wix-data';

// ...

wixData.insertReference("movies", "actors", "00001", ["12345", "67890"])
  .then( () => {
    console.log("References replaced");
  } )
  .catch( (error) => {
    console.log(error);
  } );

save( )

Inserts or updates an item in a collection.

Description

The save() function returns a Promise that resolves to the inserted or updated item after the it has been added or updated in the specified collection. The Promise is rejected if the current user does not have the necessary permissions for the collection.

The save function inserts or updates the specified item, depending on whether it already exists in the collection. It compares the _id property value of the specified item with the _id property values of the items in the specified collection. If an item in the collection has that _id value, save uses updateto update the item in the collection, triggering the beforeUpdate() and afterUpdate() hooks if they have been defined. If no items in the collection have that _id value, or if the specified item does not have an _id property, save uses insertto add the specified item into the collection, triggering the beforeInsert() and afterInsert() hooks if they have been defined.

Use the options parameter to run save() without checking for permissions or without its registered hooks.

When saving an item to a collection that has a reference field, set the value of the reference field to the referenced item's _id value or the entire referenced item object.

Syntax

function save(collectionName: string, item: Object, [options: WixDataOptions]): Promise<Object>
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The name of the collection to save the item to.
item
Object
The item to insert or update.
options(Optional)
An object with one or both of the following boolean properties: suppressAuth, suppressHooks.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Object>

Fulfilled - The item that was either inserted or updated, depending on whether it previously existed in the collection. Rejected - The error that caused the rejection.

Examples

Save an item in a collection

import wixData from 'wix-data';

// ...

let toSave = {
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe"
};

wixData.save("myCollection", toSave)
  .then( (results) => {
		let item = results; //see item below
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

/*  item is:
 *
 *  {
 *    "_id":          "rifk4nrk-dj4o-djhe-oidk-fnoqw4oiglk4i",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Save an item with a specified ID in a collection

import wixData from 'wix-data';

// ...

let toSave = {
  "_id":          "00001",
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe"
};

wixData.save("myCollection", toSave)
  .then( (results) => {
		let item = results; //see item below
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

/*  item is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Save an item in a collection using data options

import wixData from 'wix-data';

// ...

let toSave = {
  "_id":          "00001",
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe"
};

let options = {
  "suppressAuth": true,
  "suppressHooks": true
};

wixData.save("myCollection", toSave, options)
  .then( (results) => {
		let item = results; //see item below
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

/*  item is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Save an item including a reference to another item using the referenced item's ID

import wixData from 'wix-data';

// ...

let countryId = "id-of-usa-item";

let toSave = {
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe",
  "country":      countryId
};

wixData.save("myCollection", toSave)
  .then( (results) => {
    let item = results; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  item is:
 *
 *  {
 *    "_id":          "rifk4nrk-dj4o-djhe-oidk-fnoqw4oiglk4i",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe",
 *    "country":      "id-of-usa-item"
 *  }
 */

Save an item including a reference to another item using the reference item

import wixData from 'wix-data';

// ...

let countryItem = // get country item from somewhere

let toSave = {
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe",
  "country":      countryItem
};

wixData.save("myCollection", toSave)
  .then( (results) => {
    let item = results; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  item is:
 *
 *  {
 *    "_id":          "rifk4nrk-dj4o-djhe-oidk-fnoqw4oiglk4i",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe",
 *    "country":      "id-of-usa-item"
 *  }
 */

sort( )

Creates a sort to be used with the dataset setSort() function.

Description

This function is not used on its own. It is only used to create a sort for a dataset using the setSort() function.

Syntax

function sort(): WixDataSort
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
A sort object.

Examples

Sort a dataset

import wixData from 'wix-data';

// ...

$w("#myDataset").setSort( wixData.sort()
  .ascending("lastName")
  .descending("age")
);

update( )

Updates an item in a collection.

Description

The update() function returns a Promise that resolves to the updated item from the specified collection. The Promise is rejected if the current user does not have update permissions for the collection.

Calling the update() function triggers the beforeUpdate() and afterUpdate() hooks if they have been defined.

The update() function compares the _id property of the specified item with the _id property values of the items in the specified collection. If an item in the collection has that _id value, update replaced the item's property values with the ones in the specified item. If the existing item had properties with values and those properties were not included in the supplied item, the values in those properties are lost. The item's _updatedDate property is also updated to the current date.

Any valid JavaScript object can be used as a property value. The update() function maintains the structure of the specified object. For example, objects that contain nested objects, Arrays, or Arrays with nested objects are all added to the collection as defined.

Use the options parameter to run update() without checking for permissions or without its registered hooks.

When updating an item in a collection that has a reference field, set the value of the reference field to the referenced item's _id value or the entire referenced item object.

The maximum size of an item that you can update in a collection is 200kb.

Syntax

function update(collectionName: string, item: Object, [options: WixDataOptions]): Promise<Object>
PARAMETERS
?
The kind of data the property stores.
collectionName
string
The name of the collection that contains the item to update.
item
Object
The item to update.
options(Optional)
An object with one or both of the following boolean properties: suppressAuth, suppressHooks.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<Object>

Fulfilled - The object that was updated. Rejected - The error that caused the rejection.

Examples

Update an item with a specified ID in a collection

import wixData from 'wix-data';

// ...

let toUpdate = {
  "_id":          "00001",
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe"
};

wixData.update("myCollection", toUpdate)
  .then( (results) => {
		let item = results; //see item below
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

/*  item is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Update an item in a collection using data options

import wixData from 'wix-data';

// ...

let toUpdate = {
  "_id":          "00001",
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe"
};

let options = {
  "suppressAuth": true,
  "suppressHooks": true
};

wixData.update("myCollection", toUpdate, options)
  .then( (results) => {
		let item = results; //see item below
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

/*  item is:
 *
 *  {
 *    "_id":          "00001",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */

Get an item in a collection and update it

This example demonstrates the get() function followed by the update() function. When updating an item in a collection, all existing item properties must be passed to the update() function. If only the changed property is passed, the values of the other item properties will be lost. To ensure all item properties are included in the update, perform a get() on the item, change a property, and then update() the item.

import wixData from 'wix-data';

/*  existing item:
 *
 *  {
 *    "_id": "00001",
 *    "title": "Mr.",
 *	  "first_name": "John",
 *    "last_name": "Doe"
 *  }
 *
 */

wixData.get("myCollection", "00001")
  .then( (item) => {
    item.last_name = "Smith"; // updated last name
    wixData.update("myCollection", item);
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  updated item:
 *
 *  {
 *    "_id": "00001",
 *	  "title": "Mr.",
 *	  "first_name": "John",
 *    "last_name": "Smith"
 *  }
 *
 */

Query an item in a collection and update it

This example demonstrates the query() function followed by the update() function. When updating an item in a collection, all existing item properties must be passed to the update() function. If only the changed property is passed, the values of the other item properties will be lost. To ensure all item properties are included in the update, perform a query() on the item, change a property, and then update() the item.

import wixData from 'wix-data';

/*  existing item:
 *
 *  {
 *    "_id": "00001",
 *    "title": "Mr.",
 *	  "first_name": "John",
 *    "last_name": "Doe"
 *  }
 *
 */

 wixData.query("myCollection")
 		.eq("first_name", "John")
 		.eq("last_name", "Doe")
 		.find()
 		.then( (results) => {
 			let item = results.items[0];
 			item.last_name = "Smith"; // updated last name
 			wixData.update("myCollection", item);
 		} )
 		.catch( (err) => {
 			let errorMsg = err;
 		} );

/*  updated item:
 *
 *  {
 *    "_id": "00001",
 *	  "title": "Mr.",
 *	  "first_name": "John",
 *    "last_name": "Smith"
 *  }
 *
 */

Update an item including a reference to another item using the referenced item's ID

import wixData from 'wix-data';

// ...

et countryId = "id-of-usa-item";

let toUpdate = {
  "_id":          "00001",
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe",
  "country":      countryId
};

wixData.update("myCollection", toUpdate)
  .then( (results) => {
		let item = results; //see item below
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

/*  item is:
 *
 *  {
 *    "_id":          "rifk4nrk-dj4o-djhe-oidk-fnoqw4oiglk4i",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe",
 *    "country":      "id-of-usa-item"
 *  }
 */

Update an item including a reference to another item using the referenced item

import wixData from 'wix-data';

// ...

let countryItem = // get country item from somewhere

let toUpdate = {
  "_id":          "00001",
  "title":        "Mr.",
  "first_name":   "John",
  "last_name":    "Doe",
  "country":      countryItem
};

wixData.update("myCollection", toUpdate)
  .then( (results) => {
		let item = results; //see item below
	} )
	.catch( (err) => {
		let errorMsg = err;
	} );

/*  item is:
 *
 *  {
 *    "_id":          "rifk4nrk-dj4o-djhe-oidk-fnoqw4oiglk4i",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "title":        "Mr.",
 *    "first_name":   "John",
 *    "last_name":    "Doe",
 *    "country":      "id-of-usa-item"
 *  }
 */

WixDataOptions

An object that you pass as the options parameter that modifies how an operation is performed.

Description

The options parameter is an optional parameter that can be used when calling some wix-data functions. To use options, pass it a WixDataOptions object with one or both of the following key:value pairs:

  • "suppressAuth": true/false
  • "suppressHooks": true/false

The options parameter can only be used in backend code. Permission checks and hooks always run for wix-data functions called from Page, Site and Public code.

Syntax

type WixDataOptions = {
  suppressAuth: boolean
  suppressHooks: boolean
}
MEMBERS
?
The kind of data the property stores.
suppressAuth(Optional)
boolean
Prevents permission checks from running for the operation.
suppressHooks(Optional)
boolean
Prevents hooks from running for the operation.

Examples

Create a data options object

let options = {
  "suppressAuth": true,
  "suppressHooks": true
};

Use data options to prevent permission checks and hooks from running

import wixData from 'wix-data';

// ...

let options = {
  "suppressAuth": true,
  "suppressHooks": true
};

wixData.get("myCollection", "00001", options)
  .then( (results) => {
    let item = results;
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

WixDataQueryReferencedOptions

An object for controlling the order of returned referenced items.

Description

Pass a WixDataQueryReferencedOptions object when calling the queryReferenced function to control the order of the returned referenced items.

The object's order property can have the following values:

  • asc: References are returned by insertion time in ascending order.
  • desc: References are returned by insertion time in descending order.

Syntax

type WixDataQueryReferencedOptions = {
  order: boolean
}
MEMBERS
?
The kind of data the property stores.
order
boolean
The order of the returned referenced items. Either "asc" or "desc".

Examples

Get referenced items using options

import wixData from 'wix-data';

// ...

let options = {
  "order": "asc"
};

wixData.queryReferenced("movies", "00001", "actors", options)
  .then( (results) => {
    let firstItem = results.items[0]; //see item below
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  firstItem is:
 *
 *  {
 *    "_id":          "12345",
 *    "_owner":       "ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb",
 *    "_createdDate": "2017-05-24T12:33:18.938Z",
 *    "_updatedDate": "2017-05-24T12:33:18.938Z",
 *    "first_name":   "John",
 *    "last_name":    "Doe"
 *  }
 */