aggregate( )


Creates an aggregation.

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:

Method Declaration
Copy
function aggregate(collectionId: string): WixDataAggregate;
Method Parameters
collectionIdstringRequired

The ID of the collection to run the aggregation on.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.

Returns
Return Type:WixDataAggregate
JavaScript
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; });
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

bulkInsert( )


Adds a number of items to a collection.

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 an item in a collection, if the item doesn't have one or has one that is undefined. 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 500kb.

Notes:

  • If an item's _id property value is set to null or an empty string, an error is thrown.
  • Bulk operations are limited to 1000 items per function call.
  • The bulkInsert() function is not supported for Single Item Collections.
  • The bulkInsert() function does not support multi-reference fields. For multi-reference fields, use insertReference().
  • Translatable collections do not allow insertion and modification of items when working in a non-primary language. For example, if a collection's primary language is English, and the site visitor is viewing the site in French, calling bulkInsert() will fail and issue an error.
Method Declaration
Copy
function bulkInsert(
  collectionId: string,
  items: Array<object>,
  options: WixDataOptions,
): Promise<WixDataBulkResult>;
Method Parameters
collectionIdstringRequired

The ID of the collection to add the item to.

The array must contain at least one item. Passing an empty array returns an error.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


itemsArray<object>Required

The items to add.


optionsWixDataOptions

An object containing options to use when processing this operation.

Returns
Return Type:Promise<WixDataBulkResult>
JavaScript
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" * ] */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

bulkRemove( )


Removes a number of items from a collection.

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.

Notes:

  • 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.

Method Declaration
Copy
function bulkRemove(
  collectionId: string,
  itemIds: Array<string>,
  options: WixDataOptions,
): Promise<WixDataBulkRemoveResult>;
Method Parameters
collectionIdstringRequired

The ID of the collection to remove the items from.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


itemIdsArray<string>Required

IDs of the items to remove.

The array must contain at least one item. Passing an empty array returns an error.


optionsWixDataOptions

An object containing options to use when processing this operation.

Returns
Return Type:Promise<WixDataBulkRemoveResult>
JavaScript
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" * ] */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

bulkSave( )


Inserts or updates a number of items in a collection.

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 none of the items in the collection contain that _id value, the specified item does not have an _id property, or if the specified item's _id property is undefined, bulkSave() uses insert() to add the specified item into the collection. This triggers 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.

The maximum size of an item that you can save to a collection is 500kb.

Notes:

  • If an item's _id property value is set to null or an empty string, an error is thrown.
  • Bulk operations are limited to 1000 items per function call.
  • The bulkSave() function is not supported for Single Item Collections.
  • The bulkSave() function does not support multi-reference fields. For multi-reference fields, use replaceReferences() or insertReference().
  • Translatable collections do not allow insertion and modification of items when working in a non-primary language. For example, if a collection's primary language is English, and the site visitor is viewing the site in French, calling bulkSave() will fail and issue an error.
Method Declaration
Copy
function bulkSave(
  collectionId: string,
  items: Array<object>,
  options: WixDataOptions,
): Promise<WixDataBulkResult>;
Method Parameters
collectionIdstringRequired

The ID of the collection to save the item to.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


itemsArray<object>Required

The items to insert or update.

The array must contain at least one item. Passing an empty array returns an error.


optionsWixDataOptions

An object containing options to use when processing this operation.

Returns
Return Type:Promise<WixDataBulkResult>
JavaScript
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" * ] */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

bulkUpdate( )


Updates a number of items in a collection.

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.

Warning: If an existing item in the specified collection matches the _id of the specified item, bulkUpdate replaces the existing 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 500kb.

Notes:

  • Bulk operations are limited to 1000 items per function call.
  • The bulkUpdate() function is not supported for Single Item Collections.
  • The bulkUpdate() function does not support multi-reference fields. For multi-reference fields, use replaceReferences() or insertReference().
  • Translatable collections do not allow insertion and modification of items when working in a non-primary language. For example, if a collection's primary language is English, and the site visitor is viewing the site in French, calling bulkUpdate() will fail and issue an error.
Method Declaration
Copy
function bulkUpdate(
  collectionId: string,
  items: Array<object>,
  options: WixDataOptions,
): Promise<WixDataBulkResult>;
Method Parameters
collectionIdstringRequired

The ID of the collection that contains the item to update.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


itemsArray<object>Required

The items to update.

The array must contain at least one item. Passing an empty array returns an error.


optionsWixDataOptions

An object containing options to use when processing this operation.

Returns
Return Type:Promise<WixDataBulkResult>
JavaScript
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; });
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

filter( )


Creates a filter to be used with datasets and aggregations.

The filter() function builds a filter to be applied to a dataset or an aggregation, and returns a WixDataFilter object. The returned object contains the filter definition and is used with the setFilter() function.

When working with Wix app collections, check which fields can be used in a filter.

Method Declaration
Copy
function filter(): WixDataFilter;
Request
This method does not take any parameters
Returns
Return Type:WixDataFilter
Filter a dataset
JavaScript
import wixData from "wix-data"; // ... $w("#myDataset").setFilter( wixData.filter().startsWith("lastName", "D").ge("age", "21"), );
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

get( )


Retrieves an item from a collection.

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

If the specified collection contains reference fields, the ID of the referenced item is returned. To return the values of the referenced items use query() and include().

If the get() function is passed the ID of a hidden item, it returns null.

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.

Notes:

  • When using the query() or get() functions or another data retrieval method following a change to your database collection, the data retrieved may not contain your most recent changes. See Wix Data and Eventual Consistency for more information. To solve this problem, you can use the setTimeout() function to delay retrieving data following any changes to your database collection.
  • To speed up data retrieval, the results of certain data queries are cached. Learn more about caching data query results.
  • An itemId is required to retrieve an item even from a single-item collection.
Method Declaration
Copy
function get(
  collectionId: string,
  itemId: string,
  options: WixDataOptions,
): Promise<object>;
Method Parameters
collectionIdstringRequired

The ID of the collection to retrieve the item from.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


itemIdstringRequired

The ID of the item to retrieve.


optionsWixDataOptions

An object containing options to use when processing this operation.

Returns
Return Type:Promise<object>
JavaScript
import wixData from "wix-data"; // ... wixData .get("myCollection", "00001") .then((item) => { console.log(item); //see item below }) .catch((err) => { console.log(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" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

insert( )


Adds an item to a collection.

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 an item in a collection, if the item doesn't have one or has one that is undefined. 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 500kb.

Notes:

  • If an item's _id property value is set to null or an empty string, an error is thrown.
  • When creating a Single Item Collection, an item with the system field _id is pre-inserted into the collection. Single Item Collections may contain only one item.
  • If there is a pre-existing item in a Single Item Collection, the insert() function will not run. To update or change an item in a Single Item Collection see the update() and save() functions.
  • The insert() function does not support multi-reference fields. For multi-reference fields, use insertReference().
  • Translatable collections do not allow insertion and modification of items when working in a non-primary language. For example, if a collection's primary language is English, and the site visitor is viewing the site in French, calling insert() will fail and issue an error.
Method Declaration
Copy
function insert(
  collectionId: string,
  item: object,
  options: WixDataOptions,
): Promise<object>;
Method Parameters
collectionIdstringRequired

The ID of the collection to add the item to.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


itemItemRequired

The item to add.


optionsWixDataOptions

An object containing options to use when processing this operation.

Returns
Return Type:Promise<object>
JavaScript
import wixData from "wix-data"; // ... let toInsert = { title: "Mr.", first_name: "John", last_name: "Doe", }; wixData .insert("myCollection", toInsert) .then((item) => { console.log(item); //see item below }) .catch((err) => { console.log(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" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

insertReference( )


Inserts a reference in the specified property.

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.

Notes:

  • The insertReference() function only applies to multi-reference fields.
  • The insertReference() function is not supported for Single Item Collections.
Method Declaration
Copy
function insertReference(
  collectionId: string,
  propertyName: string,
  referringItem: union,
  referencedItem: union,
  options: WixDataOptions,
): Promise<void>;
Method Parameters
collectionIdstringRequired

The ID of the collection that contains the referring item.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


propertyNamestringRequired

The property to insert the reference into.


referringItemunionRequired

The referring item or referring item's ID.


referencedItemunionRequired

The referenced item, referenced item's ID, an array of referenced items, or an array of referenced item IDs.


optionsWixDataOptions

An object containing options to use when processing this operation.

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.

JavaScript
import wixData from "wix-data"; // ... wixData .insertReference("movies", "actors", "00001", "12345") .then(() => { console.log("Reference inserted"); }) .catch((error) => { console.log(error); });
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

isReferenced( )


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

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 isReferenced() function does not trigger any hooks.

Note: The isReferenced() function is not supported for Single Item Collections.

Method Declaration
Copy
function isReferenced(
  collectionId: string,
  propertyName: string,
  referringItem: union,
  referencedItem: union,
  options: WixDataOptions,
): Promise<boolean>;
Method Parameters
collectionIdstringRequired

The ID of the collection that contains the referring item.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


propertyNamestringRequired

The property that possibly contains the references to the referenced item.


referringItemunionRequired

The referring item or referring item's ID.


referencedItemunionRequired

The referenced item or referenced item's ID.


optionsWixDataOptions

An object containing options to use when processing this operation.

Returns
Return Type:Promise<boolean>
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.

JavaScript
import wixData from "wix-data"; // ... wixData .isReferenced("movies", "actors", "00001", "12345") .then((result) => { let isReferenced = result; // true }) .catch((err) => { let errorMsg = err; });
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

query( )


Creates a query for retrieving items from a database collection.

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.

If the collection that you are querying has references to other collections, by default, the data from referenced collections will not be retrieved. To get the data from the referenced items, you must either use the include() chained function before find() or use the queryReferenced() function instead of query().

Items marked as hidden in the collection are not returned.

When working with Wix app collections, fields in the collections have the following permissions:

  • Can connect to data
  • Can use in dynamic page URL
  • Can be sorted
  • Can be filtered
  • Read-only Check which fields can be used in a query.

Notes:

Method Declaration
Copy
function query(collectionId: string): WixDataQuery;
Method Parameters
collectionIdstringRequired

The ID of the collection to run the query on.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.

Returns
Return Type:WixDataQuery
JavaScript
import wixData from "wix-data"; // ... let query = wixData.query("myCollection");
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

queryReferenced( )


Gets the full items referenced in the specified property.

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.

Notes:

  • Calling the queryReferenced() function does not trigger any hooks.
  • You can only use the queryReferenced() function with multiple-item reference fields, and not with single-item (regular) reference fields.
  • The queryReferenced() function is not supported for Single Item Collections.

For a discussion of when to use the similar include() function and when to use queryReferenced(), see Querying Items that Reference Other Items.

Method Declaration
Copy
function queryReferenced(
  collectionId: string,
  item: union,
  propertyName: string,
  options: WixDataQueryReferencedOptions,
): Promise<WixDataQueryReferencedResult>;
Method Parameters
collectionIdstringRequired

The ID of the collection that contains the referring item.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


itemunionRequired

The referring item or referring item's ID.


propertyNamestringRequired

The property that contains the references to the referenced items.


optionsWixDataQueryReferencedOptions

An object for controlling the order of the returned referenced items.

Returns
Return Type:Promise<WixDataQueryReferencedResult>

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.

JavaScript
import wixData from "wix-data"; // ... wixData .queryReferenced("movies", "00001", "actors") .then((results) => { if (results.items.length > 0) { console.log(results.items[0]); //see item below } else { // handle case where no matching items found } }) .catch((err) => { console.log(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" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

remove( )


Removes an item from a collection.

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.

Notes:

  • The remove() function 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.
Method Declaration
Copy
function remove(
  collectionId: string,
  itemId: string,
  options: WixDataOptions,
): Promise<object>;
Method Parameters
collectionIdstringRequired

The ID of the collection to remove the item from.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


itemIdstringRequired

The ID of the item to remove.


optionsWixDataOptions

An object containing options to use when processing this operation.

Returns
Return Type:Promise<object>
JavaScript
import wixData from "wix-data"; // ... wixData .remove("myCollection", "00001") .then((result) => { console.log(result); // see removed item below }) .catch((err) => { console.log(err); }); /* removed 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" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

removeReference( )


Removes a reference from the specified property.

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.

Note: The removeReference() function is not supported for Single Item Collections.

Method Declaration
Copy
function removeReference(
  collectionId: string,
  propertyName: string,
  referringItem: union,
  referencedItem: union,
  options: WixDataOptions,
): Promise<void>;
Method Parameters
collectionIdstringRequired

The ID of the collection that contains the referring item.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


propertyNamestringRequired

The property to remove the reference from.


referringItemunionRequired

The referring item or referring item's ID.


referencedItemunionRequired

The referenced item, referenced item's ID, an array of referenced items, or an array of referenced item IDs.


optionsWixDataOptions

An object containing options to use when processing this operation.

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.

JavaScript
import wixData from "wix-data"; // ... wixData .removeReference("movies", "actors", "00001", "12345") .then(() => { console.log("Reference removed"); }) .catch((error) => { console.log(error); });
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

replaceReferences( )


Replaces current references with references in the specified property.

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.

Note: The replaceReferences() function is not supported for Single Item Collections.

Method Declaration
Copy
function replaceReferences(
  collectionId: string,
  propertyName: string,
  referringItem: union,
  referencedItem: union,
  options: WixDataOptions,
): Promise<void>;
Method Parameters
collectionIdstringRequired

The ID of the collection that contains the referring item.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


propertyNamestringRequired

The property to replaces the references in.


referringItemunionRequired

The referring item or referring item's ID.


referencedItemunionRequired

The referenced item, referenced item's ID, an array of referenced items, or an array of referenced item IDs.


optionsWixDataOptions

An object containing options to use when processing this operation.

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.

JavaScript
import wixData from "wix-data"; // ... wixData .replaceReferences("movies", "actors", "00001", "12345") .then(() => { console.log("References replaced"); }) .catch((error) => { console.log(error); });
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

save( )


Inserts or updates an item in a collection.

The save() function returns a Promise that resolves to the inserted or updated item after 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 none of the items in the collection contain that _id value, the specified item does not have an _id property, or if the specified item's id property is undefined, save() uses insert() to add the specified item to the collection. This triggers 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.

The maximum size of an item that you can save to a collection is 500kb.

Notes:

  • If an item's _id property value is set to null or an empty string, an error is thrown.
  • The save() function does not support multi-reference fields. For multi-reference fields, use insertReference() or replaceReferences()
  • Translatable collections do not allow insertion and modification of items when working in a non-primary language. For example, if a collection's primary language is English, and the site visitor is viewing the site in French, calling save() will fail and issue an error.
Method Declaration
Copy
function save(
  collectionId: string,
  item: object,
  options: WixDataOptions,
): Promise<object>;
Method Parameters
collectionIdstringRequired

The ID of the collection to save the item to.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


itemItemRequired

The item to insert or update.


optionsWixDataOptions

An object containing options to use when processing this operation.

Returns
Return Type:Promise<object>
JavaScript
import wixData from "wix-data"; // ... let toSave = { title: "Mr.", first_name: "John", last_name: "Doe", }; wixData .save("myCollection", toSave) .then((results) => { console.log(results); //see item below }) .catch((err) => { console.log(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" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

sort( )


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

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

When working with Wix app collections, check which fields can be used in a sort.

Method Declaration
Copy
function sort(): WixDataSort;
Request
This method does not take any parameters
Returns
Return Type:WixDataSort
Sort a dataset
JavaScript
import wixData from "wix-data"; // ... $w("#myDataset").setSort( wixData.sort().ascending("lastName").descending("age"), );
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

truncate( )


Removes all items from a collection.

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.

Method Declaration
Copy
function truncate(
  collectionId: string,
  options: WixDataOptions,
): Promise<object>;
Method Parameters
collectionIdstringRequired

The ID of the collection to remove items from.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


optionsWixDataOptions

An object containing options you can use when calling this function.

Returns
Return Type:Promise<object>
JavaScript
import wixData from "wix-data"; // ... wixData .truncate("myCollection") .then(() => { console.log("All items removed"); }) .catch((err) => { console.log(err); });
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

update( )


Updates an item in a collection.

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() 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 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 500kb.

Notes:

  • The specified item must include an _id property that already exists in the collection.
  • The update() function does not support multi-reference fields. For multi-reference fields, use replaceReferences() or insertReference().
  • Translatable collections do not allow insertion and modification of items when working in a non-primary language. For example, if a collection's primary language is English, and the site visitor is viewing the site in French, calling update() will fail and issue an error.
Method Declaration
Copy
function update(
  collectionId: string,
  item: object,
  options: WixDataOptions,
): Promise<object>;
Method Parameters
collectionIdstringRequired

The ID of the collection that contains the item to update.

To find your collectionId, select the Databases tab in the Velo Sidebar. Hover over your collection, click the three dots, and select Edit Settings.


itemItemRequired

The item to update.


optionsWixDataOptions

An object containing options to use when processing this operation.

Returns
Return Type:Promise<object>
JavaScript
import wixData from "wix-data"; // ... let toUpdate = { _id: "00001", title: "Mr.", first_name: "John", last_name: "Doe", }; wixData .update("myCollection", toUpdate) .then((results) => { console.log(results); //see item below }) .catch((err) => { console.log(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" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

Introduction

Data hooks run code before or after certain interactions with your site's collections. A data hook allows you to intercept the interaction immediately before or immediately after it occurs. The hook's code can even be used to affect the interaction itself. For example, you may want to intercept an item before it is added to your collection to perform a final validation or tweak the data that actually makes it into the collection.

In general, hooks are run whether the interaction with your collection is initiated by a page element, programmatically, or when using the Content Management System (CMS). However, a Data API call from the backend code of your site may pass the optional WixDataOptions object and use it to suppress hooks from being called on that particular operation.

Note: This feature is not yet supported in Wix Blocks.

Code for the hooks is written in the data.js file, which resides in the Backend section of your site. Hook functions are defined using the following pattern:

Copy
export function <collectionName>_<hookName>(<parameters>) { }

You can add these functions to the data.js file by writing them yourself, or by generating templates using the Velo sidebar.

To add a hook to a collection from the sidebar:

  1. Click the Databases button and hover over the relevant collection.
  2. Click the Show More icon.
  3. Select Add/Remove Hooks, and choose the hooks you want to add. Adding a Hook
Did this help?

afterCount( )


A hook that is triggered after a count() operation.

The afterCount() hook runs when:

  • The count() function is called.
  • The collection is viewed in the CMS.

Return a number or a Promise that resolves to number from the afterCount() function. The returned number will be used as the result of the call to count() instead of the actual count of items found in the collection. If returning a Promise, the number is used as the result, whether the Promise is fulfilled or rejected.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise also calls the onFailure() hook if it has been registered.

Method Declaration
Copy
function afterCount(
  count: number,
  context: HookContext,
): Promise<number> | number;
Method Parameters
countnumberRequired

The number of items the count operation has found.


contextHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<number> | number
JavaScript
// In data.js export function myCollection_afterCount(count, context) { let hookContext = context; // see below // some change to the received count return count; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

afterGet( )


A hook that is triggered after a get() operation.

The afterGet() hook runs when the get() function is called.

The hook does not run when the find function is called or when a dataset retrieves items from the collection it is connected to.

Return an object or a Promise that resolves to an object from the afterGet() function. The returned object will be used as the result of the call to the get() function instead of the actual item found in the collection. If returning a Promise, the object is used as the result, whether the Promise is fulfilled or rejected.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise also calls the onFailure() hook if it has been registered.

Method Declaration
Copy
function afterGet(item: object, context: HookContext): Promise<object> | object;
Method Parameters
itemItemRequired

The item that was retrieved from the collection.


contextHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<object> | object
JavaScript
// In data.js export function myCollection_afterGet(item, context) { let hookContext = context; // see below // some changes to the received item return item; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

afterInsert( )


A hook that is triggered after an insert() operation.

The afterInsert() hook runs when:

  • The insert() function is called.
  • An action is performed on a dataset that inserts a new item into the collection.
  • An item is inserted using the CMS.
  • An item is imported into the Sandbox or Live collection.

Return an object or a Promise that resolves to an object from the afterInsert() function. The returned object will be used as the result of the call to the insert() function instead of the actual item inserted into the collection. If returning a Promise, the object is used as the result, whether the Promise is fulfilled or rejected.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise also calls the onFailure() hook if it has been registered.

Because the afterInsert hook is called after the insert() is executed, it cannot affect the item that is inserted into the collection. It can only affect the item returned by insert().

Method Declaration
Copy
function afterInsert(
  item: object,
  context: HookContext,
): Promise<object> | object;
Method Parameters
itemItemRequired

The item that was inserted.


contextHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<object> | object
JavaScript
// In data.js export function myCollection_afterInsert(item, context) { let hookContext = context; // see below // some changes to the received item return item; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

afterQuery( )


A hook that is triggered after a find operation, for each of the items in the query results.

The afterQuery() hook runs when:

  • The find function is called.
  • An action is performed on a dataset that retrieves items from the collection.
  • The collection is viewed in the CMS.
  • An item is exported from the collection.

The hook runs once for each item in the collection.

Return an object or a Promise that resolves to an object from the afterQuery() function. The returned object will be used as the result of the call to the find function instead of the actual item found in the collection. If returning a Promise, the object is used as the result, whether the Promise is fulfilled or rejected.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise also calls the onFailure() hook if it has been registered.

Note: We recommend implementing afterQuery() with in-memory operations only. Don't use network calls such as REST API requests or other wix-data operations, as these can lead to timeouts and issues loading collection data.

Method Declaration
Copy
function afterQuery(
  item: object,
  context: HookContext,
): Promise<object> | object;
Method Parameters
itemItemRequired

One of the items of the query result. The hook is called for each item in the results.


contextHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<object> | object
JavaScript
// In data.js export function myCollection_afterQuery(item, context) { let hookContext = context; // see below // some changes to the received item return item; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

afterRemove( )


A hook that is triggered after a remove() operation.

The afterRemove() hook runs when:

  • The remove() function is called.
  • An action is performed on a dataset that removes an item from the collection.
  • An item is deleted using the CMS.

Return an object or a Promise that resolves to an object. The returned object will be used as the result of the call to the remove() function instead of the actual item removed from the collection. If returning a Promise, the object is used as the result, whether the Promise is fulfilled or rejected.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise also calls the onFailure() hook if it has been registered.

Because the afterRemove() hook is called after the remove() is executed, it cannot prevent the item from being removed from the collection. It can only affect the item returned by remove().

Method Declaration
Copy
function afterRemove(
  item: object,
  context: HookContext,
): Promise<object> | object;
Method Parameters
itemItemRequired

The item that was removed.


contextHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<object> | object
JavaScript
// In data.js export function myCollection_afterRemove(item, context) { let hookContext = context; // see below // some changes to the removed item return item; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

afterUpdate( )


A hook that is triggered after an update() operation.

The afterUpdate() hook runs when:

  • The update() function is called.
  • An action is performed on a dataset that updates an item from the collection.
  • An item is updated using the CMS.

Note: When scheduling an item's visibility change, the hook is triggered when the change is scheduled, not when it takes effect.

Return an object or a Promise that resolves to an object from the afterUpdate() function. The returned object will be used as the result of the call to the update() function instead of the actual item updated in the collection. If returning a Promise, the object is used as the result, whether the Promise is fulfilled or rejected.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise also calls the onFailure() hook if it has been registered.

Because the afterUpdate hook is called after the update() is executed, it cannot affect the item that is being updated in the collection. It can only affect the item returned by update().

Method Declaration
Copy
function afterUpdate(
  item: object,
  context: UpdateHookContext,
): Promise<object> | object;
Method Parameters
itemItemRequired

The updated item.


contextUpdateHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<object> | object
JavaScript
// In data.js export function myCollection_afterUpdate(item, context) { let hookContext = context; // see below // some changes to the received item return item; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

beforeCount( )


A hook that is triggered before a count() operation.

The beforeCount() hook runs when:

  • The count() function is called.
  • The collection is viewed in the CMS.

Return a query or a Promise that resolves to a query from the beforeCount() function. The returned query will be used as the query for the count() operation.

Often, you will modify the query that is received in the query parameter by calling one or more WixDataQuery functions.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise blocks the call to count() and also calls the onFailure() hook if it has been registered.

Because the beforeCount() hook is called before count() is executed, it can affect how items are counted or block the count().

Method Declaration
Copy
function beforeCount(
  query: WixDataQuery,
  context: HookContext,
): Promise<WixDataQuery> | WixDataQuery;
Method Parameters
queryWixDataQueryRequired

The original query as defined by count().


contextHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<WixDataQuery> | WixDataQuery
JavaScript
// In data.js export function myCollection_beforeCount(query, context) { let hookContext = context; // see below // some change to the received query return query; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

beforeGet( )


A hook that is triggered before a get() operation.

The beforeGet() hook runs when the get() function is called.

The hook does not run when the find function is called or when a dataset retrieves items from the collection it is connected to.

Return a string or a Promise that resolves to a string from the beforeGet() function. The returned string will be used as the itemId parameter for the get() operation. The item with the new itemId will be retrieved instead of the item with the original itemId.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise blocks the call to get() and also calls the onFailure() hook if it has been registered.

Because the beforeGet() hook is called before get() is executed, it can affect which item is retrieved or block the get().

Method Declaration
Copy
function beforeGet(
  itemId: string,
  context: HookContext,
): Promise<string> | string;
Method Parameters
itemIdstringRequired

The ID of the original item to be retrieved.


contextHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<string> | string
JavaScript
// In data.js export function myCollection_beforeGet(itemId, context) { let hookContext = context; // see below // change the item to get return itemId; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

beforeInsert( )


A hook that is triggered before an insert() operation.

The beforeInsert() hook runs when:

  • The insert() function is called.
  • An action is performed on a dataset that inserts a new item into the collection.
  • An item is inserted using the CMS.
  • An item is imported into the Sandbox or Live collection.

The hook also runs when an action is performed on a dataset that inserts a new item into the collection that the dataset is connected to.

Return an object or a Promise that resolves to an object from the beforeInsert() function. The returned object will be inserted into the collection instead of the original item passed to the insert() function.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise blocks the call to insert() and also calls the onFailure() hook if it has been registered.

Because the beforeInsert() hook is called before insert() is executed, it can affect the item that is inserted into the collection or block the insert().

Method Declaration
Copy
function beforeInsert(
  item: object,
  context: HookContext,
): Promise<object> | object;
Method Parameters
itemItemRequired

The original item to be inserted.


contextHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<object> | object
JavaScript
// In data.js export function myCollection_beforeInsert(item, context) { let hookContext = context; // see below // some change to the received item return item; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

beforeQuery( )


A hook that is triggered before a find() operation.

The beforeQuery() hook runs when:

  • The find function is called.
  • An action is performed on a dataset that retrieves items from the collection.
  • The collection is viewed in the CMS.
  • An item is exported from the collection.

The hook also runs when an action is performed on a dataset that retrieves items from the collection that the dataset is connected to.

Return a query or a Promise that resolves to a query from the beforeQuery() function. The returned query will be used as the query for the find operation.

Often, you will modify the query that is received in the query parameter by calling one or more WixDataQuery functions.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise blocks the call to find() and also calls the onFailure() hook if it has been registered.

Because the beforeQuery() hook is called before find() is executed, it can affect the query that is used to retrieve items or block the find().

Method Declaration
Copy
function beforeQuery(
  query: WixDataQuery,
  context: HookContext,
): Promise<WixDataQuery> | WixDataQuery;
Method Parameters
queryWixDataQueryRequired

The original query as specified by the caller.


contextHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<WixDataQuery> | WixDataQuery
JavaScript
// In data.js export function myCollection_beforeQuery(query, context) { let hookContext = context; // see below // some change to the received query return query; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

beforeRemove( )


A hook that is called before a remove() operation.

The beforeRemove() hook runs when:

  • The remove() function is called.
  • An action is performed on a dataset that removes an item from the collection.
  • An item is deleted using the CMS.

The hook also runs when an action is performed on a dataset that removes an item from the collection that the dataset is connected to.

Return a string or a Promise that resolves to a string from the beforeRemove() function. The returned string will be used as the itemId parameter for the remove() operation. The item with the new itemId will be removed instead of the item with the original itemId.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise blocks the call to remove() and also calls the onFailure() hook if it has been registered.

Because the beforeRemove() hook is called before remove() is executed, it can affect the item that is removed from the collection or block the remove().

Method Declaration
Copy
function beforeRemove(
  itemId: string,
  context: UpdateHookContext,
): Promise<string> | string;
Method Parameters
itemIdstringRequired

The ID of the original item to be removed.


contextUpdateHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<string> | string
JavaScript
// In data.js export function myCollection_beforeRemove(itemId, context) { let hookContext = context; // see below // change to the item to remove return itemId; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

beforeUpdate( )


A hook that is triggered before an update() operation.

The beforeUpdate() hook runs when:

  • The update() function is called.
  • An action is performed on a dataset that updates an item from the collection.
  • An item is updated using the CMS.

The hook also runs when an action is performed on a dataset that updates an item from the collection that the dataset is connected to.

Return an object or a Promise that resolves to an object from the beforeUpdate() function. The returned object will be updated in the collection instead of the original item passed to the update() function.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise blocks the call to update() and also calls the onFailure() hook if it has been registered.

Because the beforeUpdate() hook is called before the update() is executed, it can affect the item that is updated in the collection or block the update().

Method Declaration
Copy
function beforeUpdate(
  item: object,
  context: UpdateHookContext,
): Promise<object> | object;
Method Parameters
itemItemRequired

The original item to be updated.


contextUpdateHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<object> | object
JavaScript
// In data.js export function myCollection_beforeUpdate(item, context) { let hookContext = context; // see below // some change to the received item return item; } /* * hookContext: * * { * "collectionName": "myCollection", * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3", * "userRole": "siteOwner" * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?

onFailure( )


A hook that is triggered on any error or rejected Promise from any of the wix-data operations.

The onFailure() hook is triggered whenever a wix-data operation or hook returns a rejected Promise or an error.

Method Declaration
Copy
function onFailure(error: Error, context: HookContext): Promise<object>;
Method Parameters
errorErrorRequired

The error that caused the failure.


contextHookContextRequired

Contextual information about the hook.

Returns
Return Type:Promise<object>
A hook triggered when a failure occurs
JavaScript
// In data.js export function myCollection_onFailure(error, context) { let hookError = error; // see below // handle error return ret; } /* * hookError: * * { * "message": "An item with _id [1234] already exists.", * "code": -409 * } */
Errors

This method doesn’t return any custom errors, but may return standard errors. Learn more about standard Wix errors.

Did this help?