CorvidReference

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 functions 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 Wix Data API works with a schemaless database behind the scenes. In theory, you can store any type of data in any database collection field. In practice, each collection has a non-enforced schema that you should conform to. This schema is used to determine which page elements can connect to which fields and to provide a better experience in the Data Manager. For example, if you set a field's type to Date and Time, you can then connect that field to elements that work with dates, such as DatePicker and Text elements. Also, in the Data Manager, values will appear as dates and you can add new values using a date picker.

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 should provide the data using the JavaScript data types that correspond to your collection's field types.

Field TypeData TypeNotes
AudioJavaScript stringA Media Manager audio URL as described here.
BooleanJavaScript boolean
Date and TimeJavaScript Date object
DocumentJavaScript stringA Media Manager document URL as described here.
ImageJavaScript stringAn image URL as described here.
Media GalleryJavaScript arrayEach element in the array is either an ImageItem or VideoItem.
NumberJavaScript number
Rich TextJavaScript stringA string which can contain a subset of HTML tags.
Reference/Multiple Items ReferenceJavaScript string/JavaScript array of stringsAn item ID or multiple items IDs from the referenced collection.
TagsJavaScript string array
TextJavaScript string
TimeJavaScript stringTime in the HH.mm.ss.SSS format.
URLJavaScript stringA valid URL.
VideoJavaScript stringA video URL as described here.

Table of Contents

FUNCTIONS

?
Perform actions on an object.
aggregate( )Creates an aggregation.
bulkInsert( )Adds a number of items to a collection.
bulkRemove( )Removes a number of items from a collection.
bulkSave( )Inserts or updates a number of items in a collection.
bulkUpdate( )Updates a number of items in a collection.
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.
truncate( )Removes all items from a collection.
update( )Updates an item in a collection.

OBJECTS

?
Objects used when setting, getting, or calling the properties and methods listed above.
WixDataBulkResultAn object returned by Wix Data bulk operations.
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.

Related Content

FAQ

    Why don't I see my database content displayed in my site elements?
    How do I populate a repeater with data from a query?
    How do I update some fields for a collection item without deleting the values in the items other fields?
    How do I limit the number of items returned by a query?
    How do I retrieve the items referenced by another item?
    Why is my data operation working in preview, but not in my published site?
    How do I bypass permissions checks when performing a data operation?

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
?
Values that you pass to a function.
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) => {
    if (results.items.length > 0) {
      let items = results.items;
      let numItems = results.length;
      let hasNext = results.hasNext();  
    } else {
      // handle case where no matching items found
    }
  } )
  .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) => {
    if (results.items.length > 0) {
      let items = results.items;
      let numItems = results.length;
      let hasNext = results.hasNext();
    } else {
      // handle case where no matching items found
    }
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );

bulkInsert( )

Adds a number of items to a collection.

Description

The bulkInsert() function returns a Promise that resolves after the items have been added to the specified collection. The Promise is rejected if the current user does not have create permissions for the collection. Items are skipped if they include an _id property whose value matches an existing ID in the collection. Meaning, bulkInsert() cannot overwrite an existing item in the collection.

Calling the bulkInsert() function triggers the beforeInsert() and afterInsert() hooks for each item that is inserted if the hooks have been defined.

Use the options parameter to run bulkInsert() from backend code without checking for permissions or without its registered hooks.

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

The bulkInsert() 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 bulkInsert() 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.

Note

Bulk operations are limited to 1000 items per function call.

Syntax

function bulkInsert(collectionName: string, items: Array<Object>, [options: WixDataOptions]): Promise<WixDataBulkResult>
PARAMETERS
?
Values that you pass to a function.
collectionName
string
The name of the collection to add the item to.
items
Array<Object>
The items 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.

Fulfilled - The results of the bulk insert. Rejected - The error that caused the rejection.

Examples

Insert multiple items into a collection

import wixData from 'wix-data';

// ...

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

let toInsert2 = {
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe"
};

wixData.bulkInsert("myCollection", [toInsert1, toInsert2])
  .then( (results) => {
    let inserted = results.inserted; // 2
    let insertedIds = results.insertedItemIds; // see below
    let updated = results.updated; // 0
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  insertedIds is:
 *
 *  [
 *    "d9ea65a6-726a-4c3e-b97d-1128c0a06b5f",
 *    "472c1da9-e5e4-4620-8ee3-962e9d1a7df5"
 *  ]
 */

Insert multiple items with specified IDs into a collection

import wixData from 'wix-data';

// ...

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

let toInsert2 = {
  "_id":          "00002",
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe"
};

wixData.bulkInsert("myCollection", [toInsert1, toInsert2])
  .then( (results) => {
    let inserted = results.inserted; // 2
    let insertedIds = results.insertedItemIds; // ["00001", "00002"]
    let updated = results.updated; // 0
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

Insert multiple items into a collection using data options

import wixData from 'wix-data';

// ...

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

let toInsert2 = {
  "_id":          "00002",
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe"
};

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

wixData.bulkInsert("myCollection", [toInsert1, toInsert2], options)
  .then( (results) => {
    let inserted = results.inserted; // 2
    let insertedIds = results.insertedItemIds; // ["00001", "00002"]
    let updated = results.updated; // 0
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

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

import wixData from 'wix-data';

// ...

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

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

let toInsert2 = {
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe",
  "country":      countryId
};

wixData.bulkInsert("myCollection", [toInsert1, toInsert2])
  .then( (results) => {
    let inserted = results.inserted; // 2
    let insertedIds = results.insertedItemIds; // see below
    let updated = results.updated; // 0
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  insertedIds is:
 *
 *  [
 *    "d9ea65a6-726a-4c3e-b97d-1128c0a06b5f",
 *    "472c1da9-e5e4-4620-8ee3-962e9d1a7df5"
 *  ]
 */

Insert multiple items including a reference to another item using the reference item

import wixData from 'wix-data';

// ...

let countryItem = // get country item from somewhere

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

let toInsert2 = {
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe",
  "country":      countryItem
};

wixData.bulkInsert("myCollection", [toInsert1, toInsert2])
  .then( (results) => {
    let inserted = results.inserted; // 2
    let insertedIds = results.insertedItemIds; // see below
    let updated = results.updated; // 0
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  insertedIds is:
 *
 *  [
 *    "d9ea65a6-726a-4c3e-b97d-1128c0a06b5f",
 *    "472c1da9-e5e4-4620-8ee3-962e9d1a7df5"
 *  ]
 */

bulkRemove( )

Removes a number of items from a collection.

Description

The bulkRemove() function returns a Promise that resolves after the items have been removed from the specified collection. The Promise is rejected if the current user does not have delete permissions for the collection. If the delete permissions for the collection are set to Site member author, the only items that will be deleted are those for which the current user is the owner. All other items will be skipped.

Calling the bulkRemove() function triggers the beforeRemove() and afterRemove() hooks for each item that is deleted if the hooks have been defined.

Use the options parameter to run bulkRemove() from backend code without checking for permissions or without its registered hooks.

Note

The bulkRemove() function also clears multiple-item reference fields for items in collections referenced by the specified items. For example, suppose you have a Movies collection with an Actors field that contains multiple references to items in a People collection. Removing items in the Movies collection also clears the data in the corresponding multiple-item reference fields in the People collection.

Bulk operations are limited to 1000 items per function call.

Syntax

function bulkRemove(collectionName: string, itemIds: Array<string>, [options: WixDataOptions]): Promise<WixDataBulkResult>
PARAMETERS
?
Values that you pass to a function.
collectionName
string
The name of the collection to remove the items from.
itemIds
Array<string>
IDs of the items 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.

Fulfilled - The results of the bulk remove. Rejected - The error that caused the rejection.

Examples

Remove multiple items from a collection

import wixData from 'wix-data';

// ...

let toRemove = ["00001", "00003", "00004"];

wixData.bulkRemove("myCollection", toRemove)
  .then( (results) => {
    let removed = results.removed; // 2
    let removedIds = results.removedItemIds; // see below
    let skipped = results.skipped; // 0
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  removedIds is:
 *
 *  [
 *    "00001",
 *    "00002",
 *    "00003"
 *  ]
 */

Remove multiple items from a collection using data options

import wixData from 'wix-data';

// ...

let toRemove = ["00001", "00003", "00004"];

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

wixData.bulkRemove("myCollection", toRemove, options)
  .then( (results) => {
    let removed = results.removed; // 2
    let removedIds = results.removedItemIds; // see below
    let skipped = results.skipped; // 0
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  removedIds is:
 *
 *  [
 *    "00001",
 *    "00002",
 *    "00003"
 *  ]
 */

bulkSave( )

Inserts or updates a number of items in a collection.

Description

The bulkSave() function returns a Promise that resolves after the items have 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 bulkSave function inserts or updates the specified items, depending on whether they already exist in the collection. It compares the _id property value of the specified items with the _id property values of the items in the specified collection.

  • If an item in the collection has the specified _id value, bulkSave uses update to update the item in the collection, triggering the beforeUpdate() and afterUpdate() hooks for that item 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, bulkSave uses insert to add the specified item into the collection, triggering the beforeInsert() and afterInsert() hooks for that item if they have been defined.

Use the options parameter to run bulkSave() from backend code without checking for permissions or without its registered hooks.

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

Note

Bulk operations are limited to 1000 items per function call.

Syntax

function bulkSave(collectionName: string, items: Array<Object>, [options: WixDataOptions]): Promise<WixDataBulkResult>
PARAMETERS
?
Values that you pass to a function.
collectionName
string
The name of the collection to save the item to.
items
Array<Object>
The items 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.

Fulfilled - The results of the bulk save. Rejected - The error that caused the rejection.

Examples

Save multiple items in a collection

import wixData from 'wix-data';

// ...

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

let toSave2 = {
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe"
};

wixData.bulkSave("myCollection", [toSave1, toSave2])
  .then( (results) => {
    let inserted = results.inserted; // 2
    let insertedIds = results.insertedItemIds; // see below
    let updated = results.updated; // 0
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  insertedIds is:
 *
 *  [
 *    "d9ea65a6-726a-4c3e-b97d-1128c0a06b5f",
 *    "472c1da9-e5e4-4620-8ee3-962e9d1a7df5"
 *  ]
 */

Save multiple items with specified IDs in a collection

import wixData from 'wix-data';

// ...

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

let toSave2 = {
  "_id":          "00003",
  "title":        "Prof.",
  "first_name":   "Jan",
  "last_name":    "Doey"
};

wixData.bulkSave("myCollection", [toSave1, toSave2])
  .then( (results) => {
    let inserted = results.inserted; // 1
    let insertedIds = results.insertedItemIds; // ["00003"]
    let updated = results.updated; // 1
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

Save multiple items in a collection using data options

import wixData from 'wix-data';

// ...

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

let toSave2 = {
  "_id":          "00003",
  "title":        "Prof.",
  "first_name":   "Jan",
  "last_name":    "Doey"
};

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

wixData.bulkSave("myCollection", [toSave1, toSave2], options)
  .then( (results) => {
    let inserted = results.inserted; // 1
    let insertedIds = results.insertedItemIds; // ["00003"]
    let updated = results.updated; // 1
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

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

import wixData from 'wix-data';

// ...

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

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

let toSave2 = {
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe",
  "country":      countryId
};

wixData.bulkSave("myCollection", [toSave1, toSave2])
  .then( (results) => {
    let inserted = results.inserted; // 2
    let insertedIds = results.insertedItemIds; // see below
    let updated = results.updated; // 0
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  insertedIds is:
 *
 *  [
 *    "d9ea65a6-726a-4c3e-b97d-1128c0a06b5f",
 *    "472c1da9-e5e4-4620-8ee3-962e9d1a7df5"
 *  ]
 */

Save multiple items including a reference to another item using the reference item

import wixData from 'wix-data';

// ...

let countryItem = // get country item from somewhere

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

let toSave2 = {
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe",
  "country":      countryItem
};

wixData.bulkSave("myCollection", [toSave1, toSave2])
  .then( (results) => {
    let inserted = results.inserted; // 2
    let insertedIds = results.insertedItemIds; // see below
    let updated = results.updated; // 0
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  insertedIds is:
 *
 *  [
 *    "d9ea65a6-726a-4c3e-b97d-1128c0a06b5f",
 *    "472c1da9-e5e4-4620-8ee3-962e9d1a7df5"
 *  ]
 */

bulkUpdate( )

Updates a number of items in a collection.

Description

The bulkUpdate() function returns a Promise that resolves after the items have been updated in the specified collection. The Promise is rejected if the current user does not have update permissions for the collection. Items are skipped if they include an _id property whose value does not match an existing ID in the collection. Meaning, bulkUpdate() cannot add new items into the collection.

Calling the bulkUpdate() function triggers the beforeUpdate() and afterUpdate() hooks for each item that is updated if the hooks have been defined.

The bulkUpdate() function compares the _id property of the specified items with the _id property values of the items in the specified collection.

If an item in the collection has that _id value, bulkUpdate replaces 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 specified 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 bulkUpdate() 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 bulkUpdate() from backend code without checking for permissions or without its registered hooks.

When updating items in a collection that has a reference field, set the values 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.

Note

Bulk operations are limited to 1000 items per function call.

Syntax

function bulkUpdate(collectionName: string, items: Array<Object>, [options: WixDataOptions]): Promise<WixDataBulkResult>
PARAMETERS
?
Values that you pass to a function.
collectionName
string
The name of the collection that contains the item to update.
items
Array<Object>
The items 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.

Fulfilled - The results of the bulk save. Rejected - The error that caused the rejection.

Examples

Update multiple items with specified IDs in a collection

import wixData from 'wix-data';

// ...

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

let toUpdate2 = {
  "_id":          "00002",
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe"
};

wixData.bulkUpdate("myCollection", [toUpdate1, toUpdate2])
  .then( (results) => {
    let inserted = results.inserted; // 0
    let insertedIds = results.insertedItemIds; // []
    let updated = results.updated; // 2
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

Update multiple items in a collection using data options

import wixData from 'wix-data';

// ...

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

let toUpdate2 = {
  "_id":          "00002",
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe"
};

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

wixData.bulkUpdate("myCollection", [toUpdate1, toUpdate2], options)
  .then( (results) => {
    let inserted = results.inserted; // 0
    let insertedIds = results.insertedItemIds; // []
    let updated = results.updated; // 2
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

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

import wixData from 'wix-data';

// ...

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

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

let toUpdate2 = {
  "_id":          "00002",
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe",
  "country":      countryId
};

wixData.bulkUpdate("myCollection", [toUpdate1, toUpdate2])
  .then( (results) => {
    let inserted = results.inserted; // 0
    let insertedIds = results.insertedItemIds; // []
    let updated = results.updated; // 2
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

Update multiple items including a reference to another item using the referenced item

import wixData from 'wix-data';

// ...

let countryItem = // get country item from somewhere

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

let toUpdate2 = {
  "_id":          "00002",
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe",
  "country":      countryItem
};

wixData.bulkUpdate("myCollection", [toUpdate1, toUpdate2])
  .then( (results) => {
    let inserted = results.inserted; // 0
    let insertedIds = results.insertedItemIds; // []
    let updated = results.updated; // 2
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

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() from backend code without checking for permissions or without its registered hooks.

Syntax

function get(collectionName: string, itemId: string, [options: WixDataOptions]): Promise<Object>
PARAMETERS
?
Values that you pass to a function.
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() from backend code 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
?
Values that you pass to a function.
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
?
Values that you pass to a function.
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
?
Values that you pass to a function.
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 onto the query. WixDataQuery functions enable you to sort, filter, and control the 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
?
Values that you pass to a function.
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) => {
    if(results.items.length > 0) {
      let firstItem = results.items[0]; //see item below
    } else {
      // handle case where no matching items found
    }
  } )
  .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) => {
    if(results.items.length > 0) {
      let firstItem = results.items[0]; //see item below
    } else {
      // handle case where no matching items found
    }
  } )
  .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) => {
      if(results.items.length > 0) {
        $w("#myTable").rows = results.items;
      } else {
        $w("#myTable").collapse();
      }
    } );
}

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<WixDataQueryReferencedResult>
PARAMETERS
?
Values that you pass to a function.
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.

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) => {
    if(results.items.length > 0) {
      let firstItem = results.items[0]; //see item below
    } else {
      // handle case where no matching items found
    }
  } )
  .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) => {
    if(results.items.length > 0) {
      let firstItem = results.items[0]; //see item below
    } else {
      // handle case where no matching items found
    }
  } )
  .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 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() from backend code without checking for permissions or without its registered hooks.

Note

remove() also clears multiple-item reference fields for items in collections referenced by the specified item. For example, suppose you have a Movies collection with an Actors field that contains multiple references to items in a People collection. Removing an item in the Movies collection also clears the data in the corresponding multiple-item reference fields in the People collection.

Syntax

function remove(collectionName: string, itemId: string, [options: WixDataOptions]): Promise<Object>
PARAMETERS
?
Values that you pass to a function.
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) => {
    if(results.items.length > 0) {
      let firstItem = results.items[0]; //see item below
    } else {
      // handle case where no matching items found
    }
  } )
  .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
?
Values that you pass to a function.
collectionName
string
The name of the collection that contains the referring item.
propertyName
string
The property to remove the reference from.
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 removed");
  } )
  .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 removed");
  } )
  .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
?
Values that you pass to a function.
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 update to 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 insert to 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() from backend code 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
?
Values that you pass to a function.
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")
);

truncate( )

Removes all items from a collection.

Description

The truncate() function returns a Promise that resolves after all items have been removed from the specified collection.

truncate() runs when at least one of the following is true:

  • The current user is the site owner.
  • The request is performed in backend code with a suppressAuth options value of true.

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

Note

truncate() also clears multiple-item reference fields in collections referenced by the specified collection. For example, suppose you have a Movies collection with an Actors field that contains multiple references to items in a People collection. Truncating the Movies collection also clears the data in the corresponding multiple-item reference field in the People collection.

Syntax

function truncate(collectionName: string, [options: WixDataOptions]): Promise<void>
PARAMETERS
?
Values that you pass to a function.
collectionName
string
The collection to remove items from.
options(Optional)
An object with the following boolean property: suppressAuth.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>

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

Examples

Site owner removes all items from a collection

import wixData from 'wix-data';

// ...

wixData.truncate("myCollection")
  .then( () => {
    console.log("All items removed");
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

User who is not the site owner removes all items from a collection in the backend using data options

import wixData from 'wix-data';

// ...

let options = {
  "suppressAuth": true
};

wixData.truncate("myCollection", options)
  .then( () => {
    console.log("All items removed");
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

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 specified 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() from backend code 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
?
Values that you pass to a function.
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) => {
      if(results.items.length > 0) {
        let item = results.items[0];
        item.last_name = "Smith"; // updated last name
        wixData.update("myCollection", item);
      } else {
        // handle case where no matching items found
      }
    } )
    .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"
 *  }
 */

WixDataBulkResult

An object returned by Wix Data bulk operations.

Syntax

type WixDataBulkResult = {
  inserted: number
  updated: number
  skipped: number
  insertedItemIds: Array<string>
  errors: Array<Error>
  removed: number
  removedItemIds: Array<string>
}
MEMBERS
?
The properties of an object.
inserted
number
The number of inserted items.
updated
number
The number of updated items.
skipped
number
The number of skipped items.
insertedItemIds
Array<string>
List of IDs of inserted items.
errors
Array<Error>
List of errors.
removed
number
The number of removed items.
removedItemIds
Array<string>
List of IDs of removed items.

Examples

Insert multiple items into a collection

import wixData from 'wix-data';

// ...

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

let toInsert2 = {
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe"
};

wixData.bulkInsert("myCollection", [toInsert1, toInsert2])
  .then( (results) => {
    let inserted = results.inserted; // 2
    let insertedIds = results.insertedItemIds; // see below
    let updated = results.updated; // 0
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  insertedIds is:
 *
 *  [
 *    "d9ea65a6-726a-4c3e-b97d-1128c0a06b5f",
 *    "472c1da9-e5e4-4620-8ee3-962e9d1a7df5"
 *  ]
 */

Save multiple items in a collection

import wixData from 'wix-data';

// ...

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

let toSave2 = {
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe"
};

wixData.bulkSave("myCollection", [toSave1, toSave2])
  .then( (results) => {
    let inserted = results.inserted; // 2
    let insertedIds = results.insertedItemIds; // see below
    let updated = results.updated; // 0
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  insertedIds is:
 *
 *  [
 *    "d9ea65a6-726a-4c3e-b97d-1128c0a06b5f",
 *    "472c1da9-e5e4-4620-8ee3-962e9d1a7df5"
 *  ]
 */

Update multiple items with specified IDs in a collection

import wixData from 'wix-data';

// ...

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

let toUpdate2 = {
  "_id":          "00002",
  "title":        "Ms.",
  "first_name":   "Jane",
  "last_name":    "Doe"
};

wixData.bulkUpdate("myCollection", [toUpdate1, toUpdate2])
  .then( (results) => {
    let inserted = results.inserted; // 0
    let insertedIds = results.insertedItemIds; // []
    let updated = results.updated; // 2
    let skipped = results.skipped; // 0
    let errors = results.errors; // []
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

Remove multiple items from a collection

import wixData from 'wix-data';

// ...

let toRemove = ["00001", "00003", "00004"];

wixData.bulkRemove("myCollection", toRemove)
  .then( (results) => {
    let removed = results.removed; // 2
    let removedIds = results.removedItemIds; // see below
    let skipped = results.skipped; // 0
  } )
  .catch( (err) => {
    let errorMsg = err;
  } );

/*  removedIds is:
 *
 *  [
 *    "00001",
 *    "00002",
 *    "00003"
 *  ]
 */

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 properties of an object.
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: string
}
MEMBERS
?
The properties of an object.
order
string
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) => {
    if(results.items.length > 0) {
      let firstItem = results.items[0]; //see item below
    } else {
      // handle case where no matching items found
    }
  } )
  .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"
 *  }
 */