The Data API allows you to interact programmatically with your site's database collections.
With the Data API, you can:
For more information, see Working with the Data API and Overview of the Wix Data and Wix Dataset APIs.
Get hands-on experience with the Data API on our Hello Data example page.
To use the data module, import wixData
from the wix-data
module:
import wixData from "wix-data";
It's important to note the following points before starting to code:
The Data API can be used in your site’s frontend or backend code.
The maximum size of an item that you can save to a collection is 500 kb.
When using data retrieval methods such as query()
or get()
following a change to your database collection, the data retrieved may not yet contain your most recent changes. See Wix Data and Eventual Consistency for more information.
To speed up data retrieval, the results of certain data queries are cached. Learn more about caching data query results.
When querying Wix App Collections, check which fields can be filtered in the relevant collection field article.
When your site makes a data request, it may take some time to receive a response. Wix Data places limits on how long a response can take before the request times out. If the response time exceeds this limit, Wix Data returns an error instead of the intended result.
Updating a collection item replaces the existing database item. If the existing item had properties with values and those properties are not included in the updated item, the values in those properties are lost.
Aggregations can only be used on collections you created. They cannot be used on Wix App Collections.
Some functions don't apply to Single Item Collections.
Depending on the permissions defined for your database collection,
your site visitors may not have the permissions required to run a specific function. A function called with insufficient permissions will fail. When necessary, you can override permission
checks in backend code by using the SuppressAuth
option.
You can connect external database collections to your Wix site and use any of the Wix Data APIs to manage and retrieve data from those collections.
Aggregate: Perform calculations on collection data to retrieve meaningful summaries.
Distinct: Function that returns the distinct values that match a query, without duplicates.
Hooks: Hooks run code before or after certain interactions with your site's collections, sometimes allowing you to interact with
the data handled in the interaction. For example, you can use the beforeInsert()
hook to capitalize text before it's inserted into a collection.
Query: Retrieve information from a database.
Reference field: Fields in a database collection that let you link one collection with other collections. Specifically, a reference field associates an item in one collection with an item in a different collection.
Truncate: Removes all items from a collection.
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 Content Management System (CMS). 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 CMS, 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 Type | Data Type | Notes |
---|---|---|
Address | JavaScript object | An Address object as described here. |
Array | JavaScript array | |
Audio | JavaScript string | A Media Manager audio URL as described here. |
Boolean | JavaScript boolean | |
Date and Time | JavaScript Date object | Note that Javascript Date Objects are displayed as strings. Learn more about Date Fields. |
Date | JavaScript string | A date in ISO 8601 date format (YYYY-MM-DD). Learn more about Date Fields. |
Document | JavaScript string | A Media Manager document URL in the following format: wix:document:// . |
Image | JavaScript string | An image URL as described here. |
Media Gallery | JavaScript array | Each element in the array is either an ImageItem or VideoItem as described here. |
Number | JavaScript number | |
Object | JavaScript object | |
Rich Text | JavaScript string | A string which can contain a subset of HTML tags. |
Reference/Multiple Items Reference | JavaScript string/JavaScript array of strings | An item ID or multiple items IDs from the referenced collection. |
Tags | JavaScript string array | |
Text | JavaScript string | |
Time | JavaScript string | Time in the HH.mm.ss.SSS format. |
URL | JavaScript string | A valid URL. |
Video | JavaScript string | A video URL as described here. |
Wix Data stores your data in a primary database instance, as well as several geographically dispersed mirror instances. The wix-data API is eventually consistent, meaning that it always updates your data in the primary database instance first, then propagates your changes to the mirror instances. When you update your database collection, there may be a short delay (typically a few seconds) until all mirror instances are up to date with your recent changes.
When you call a data retrieval function, your request goes to the closest mirror database instance. This saves time, as the request and response don't have to travel as far. However,
if you attempt to retrieve data shortly after updating it, your latest changes may not yet be reflected in the data you get back. For example, initially wixData.get('Collection', 'x');
may resolve to
null
following wixData.insert('Collection', { _id: 'x' });
.
If you need a data retrieval function to get fully up-to-date data immediately after an update, you can set the consistentRead
property in the options
parameter to true
. For example:
import wixData from "wix-data";
let options = {
consistentRead: true,
};
wixData
.get("myCollection", "00001", options)
.then((item) => {
console.log(item);
})
.catch((err) => {
console.log(err);
});
This slows down the operation but ensures the data is retrieved from the up-to-date primary database instance.
Wix places quotas on requests made by your site using the wix-data API. These quotas affect the number of requests your site can make per minute and the amount of time your requests can run for. Learn more about data quotas and how to work with them.
When you use the Wix Data API, you may encounter errors. This list includes the error codes and messages returned by the API and more information to help you resolve issues. If an error persists, contact support for help.
Code | Message | Description |
---|---|---|
WDE0001 | Collection name must be a string. | Check that the collection name you provided is a valid string. |
WDE0002 | Item ID must be a string. | Check that the item _id you provided is a valid string. |
WDE0003 | Field name must be a string. | Check that the field name you provided is a valid string. |
WDE0004 | Failed to save {item name} into {collection name}. Items must be JavaScript objects. | Check that the item you're saving is a valid JavaScript object. |
WDE0005 | Failed to bulk save items into {collection name}. Items must be an array of JavaScript objects and item IDs must be strings if present. | One or more of the items you tried to save was invalid. Check that the items are an array of valid JavaScript objects and that any _id properties in the items are strings. A valid ID key-value pair looks like this:'_id': 'ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb' . |
WDE0006 | Failed to bulk save items into {collection name}. Cannot insert more than 1000 items in one request. | You tried to save too many items at once. Avoid this error by splitting up your request into batches of fewer than 1000 items. |
WDE0007 | Invalid update. Updated object must have an _id property that is a string. | Check that the object you passed for the item parameter has a property called _id whose value is a valid string. |
WDE0008 | wixData.{the function you called} expects between {minimum} and {maximum} arguments, but was called with {the number of arguments you provided}. | The wrong number of arguments were passed to the function. Check your code to make sure that you are passing a valid number of arguments, and that you separate the argument values with commas. |
WDE0009 | Document is too large. | The maximum size for a single collection item is 512 KB. Check that the items you're adding are smaller than this. |
WDE0011 | Invalid filter usage. .filter requires WixDataFilter. | Check that the argument passed to the WixDataAggregate filter() function is a valid WixDataFilter object. |
WDE0012 | Invalid {function you called} usage. Filter is already set. | You are trying to use this function to set a filter, but you've already set one. You can only set one filter at a time. Check your code to see where the previous filter was set. |
WDE0013 | Invalid group usage. Group is already set. | You are trying to use the group() function to set a group for your aggregation, but you've already set one. You can only set one group at a time. Check your code to see where the previous group was set. |
WDE0014 | Requests per minute quota exceeded. | Your site has exceeded the quota of the maximum number of data requests per minute. Learn more about this quota and how to prevent this error. |
WDE0016 | Filter must be an object. | Check that your filter is a valid WixDataFilter object. See the API Reference to learn how to build one. |
WDE0018 | Options must be an object with one or all of the following boolean properties: {expected properties for your function} | Check that the options object you provided for a function is valid. For example, the save() function accepts 2 optional properties in its options parameter, supressAuth , and supressHooks . Defining an options parameter that has one of those properties whose value isn't a boolean results in an error. To find the appropriate options properties for the function you're using, consult the API Reference. |
WDE0019 | Reference operation takes a string ID or an object with an ID to be connected. | Check that the argument passed to a function dealing with reference fields is either an item ID string or an object with an _id field. This error applies to the referringItem and referencedItem parameters of the isReferenced() , replaceReferences() , and removeReference() functions and the item parameter of queryReferenced() function. |
WDE0020 | Provided relationship attribute {your field name} is not a multi-reference field. | Check that the collection field you're adding a multi-reference value to is a multi-reference type. |
WDE0021 | Invalid reference | Check that the referring and referenced items you provided are valid. A valid referring item is either an _id string or an object with an _id property. A valid referenced item is either an _id string, an object with an _id property, or an array of _id strings. |
WDE0024 | Field is deleted | The field you're trying to access was deleted. Restore the collection in the Content Management System (CMS) before using the field in your code. |
WDE0025 | The {your collection name} collection does not exist. You cannot work with a collection using the Data API before it is created in the Editor. | Check that the collection you're trying to access exists on your site. |
WDE0027 | The current user does not have permissions to {some action} on the {your collection name} collection. | A data request was made with insufficient permissions. Set up your collections permissions based on your site's needs. |
WDE0028 | Operation time limit exceeded. | Your data request ran for more than 5 seconds and timed out. The request was terminated. If this error persists, it may be because your request is working with large amounts of data. Learn more about this quota and how to prevent this error. |
WDE0029 | Reference {referencingCollectionName.propertyName} from {referencingItemId} to {referencedItemId} already exists. | The reference you're trying to create already exists. |
WDE0032 | Invalid {operator} parameter {operand}. {operator} parameter must be a {specifier} number. | The argument passed to this function must be a valid number. |
WDE0033 | Invalid {operator} parameter {operand}. {operator} parameter must be a positive number. | When calling limit() , the argument passed to this function must be a positive number. |
WDE0034 | Invalid {operator} parameter {operand}. {operator} parameter must be a non-negative number. | When calling skip() , the argument passed to this function must be a non-negative number. |
WDE0035 | Invalid {operator} parameter {operand}. {operator} parameter must be an integer. | The argument passed to this function must be an integer. |
WDE0036 | Invalid {operator} parameter {operand}. {operator} parameter cannot exceed {value}. | The argument passed to this function cannot be larger than the specified value. |
WDE0037 | Invalid query on {collection name}. Invalid prev positioned query skip on a negative number. | Check that the skip value you provided for the query is 0 or greater. |
WDE0038 | Invalid {operator} usage. {operator} does not take parameters. | This function expects no arguments. |
WDE0039 | Invalid {operator} usage. {operator} requires one parameter. | This function expects exactly one argument. |
WDE0040 | Invalid {operator} usage. {operator} requires two parameters. | This function expects exactly two arguments. |
WDE0041 | Invalid {operator} usage. {operator} requires three parameters. | This function expects exactly three arguments. |
WDE0042 | Invalid {operator} usage. {operator} requires at least two parameters. | This function expects at least two arguments, but fewer were provided. |
WDE0043 | Invalid {operator} usage. {operator} requires at least one parameter. | This function expects at least one argument, but none were provided. |
WDE0044 | Invalid {function name} parameter value. {function name} parameter must be a string. | The argument passed to this function must be a string. |
WDE0045 | Invalid {operator} parameter value {value}. Valid {operator} parameter types are string, Number or Date. | The argument passed to this function must be a string, number, or date object. |
WDE0046 | Invalid {operator} parameter values {first} and {second}. Both parameters must be of the same type. | The arguments to this function must be of the same type. |
WDE0047 | Invalid {operator} usage. {operator} supports only number, string or date items. | The arguments to this function must be strings, numbers, or date objects. |
WDE0048 | Invalid {operator} field value {field}. {operator} field must be a string. | This field value must be a string. |
WDE0049 | Invalid {operator} parameter {obj}. {operator} expects {constructor name} only. | The argument passed to this function must be a valid Wix Data Query object. |
WDE0050 | Invalid {operator} parameter query for {collection name}. {operator} accepts {constructor name} for the same collection only. | You can only chain functions that query the same collection. |
WDE0051 | Invalid {operator} parameters {effective arguments}. Valid {operator} values are string, array of strings, or varargs string. | This function expects a string, an array of strings, or multiple strings (varargs) separated by commas. For example: ("key1", "key2") . |
WDE0052 | The current site is in template mode. Please save it to modify data. | To modify collection data on a site created from a template, make sure to save the site first. |
WDE0053 | Internal wixData error: {error message} | An unexpected error occurred. If the error persists, contact support. |
WDE0054 | WD_UNKNOWN_ERROR | An internal server error. Try running your code again. |
WDE0055 | Failed to parse server response. | Wix Data could not parse the server response. Try querying again. |
WDE0056 | {operator} should be an Object. Got {value} instead. | The argument passed to this function must be a valid object. Learn more about data types in Wix Data. |
WDE0057 | {operator} should be an Array. Got {value} instead. | The argument passed to this function must be a valid array. Learn more about data types in Wix Data. |
WDE0058 | {operator} should be a Date, number, or string. Got {value} instead. | The argument passed to this function must be a valid date object, a number, or a string. Learn more about data types in Wix Data. |
WDE0059 | {operator} should be a string. Got {value} instead | The argument passed to this function must be a valid string. Learn more about data types in Wix Data. |
WDE0060 | {operator} array should only contain values of types date, number, and string. Got {value} instead. | The array can only contain dates, objects, numbers, and strings. Learn more about data types in Wix Data. |
WDE0061 | {$in} Array should have length 2, and match { String, Number }. Got {value} instead. | Invalid parameter types. Learn more about data types in Wix Data. |
WDE0062 | $matches value {value} does not have property {property name} | Wix Data error encountered. Try modifying your query. If this error persists, contact support. |
WDE0063 | $matches.ignoreCase should equal true. Got {value} instead | Wix Data error encountered. Try modifying your query. If this error persists, contact support. |
WDE0064 | $matches.spec array values should be either {{"type":"anyOf","value":" -"}} or {{"type":"literal","value":String}}. Got {value} instead | Wix Data error encountered. Try modifying your query. If this error persists, contact support. |
WDE0065 | Sort Model should be an Array. Got {value} instead. | Wix Data error encountered. Try modifying your query. If this error persists, contact support. |
WDE0066 | Sort Model Array should contain values of type Object only. Got {value} instead | Wix Data error encountered. Try modifying your query. If this error persists, contact support. |
WDE0067 | Sort Model Array items should have a single property with value "asc" or "desc". Got {value} instead | Wix Data error encountered. Try modifying your query. If this error persists, contact support. |
WDE0068 | Item IDs must be an array of strings. | Check that the bulkRemove() function received an array of strings representing the IDs of the items you want to remove as its second argument.For example, ['ffdkj9c2-df8g-f9ke-lk98-4kjhfr89keedb', 'afthj8s4-dt7u-g4fr-at23-6joedh34awshy'] . |
WDE0069 | Failed to remove items from {collection name}. Cannot remove more than 1000 items in one request. | You tried to remove too many items from a collection at once. Split your request into batches of 1000 items or fewer. To remove all the items in a collection, use truncate() . |
WDE0070 | {regex} keyword is not allowed. | Wix Data error encountered. Try modifying your query. If this error persists, contact support. |
WDE0073 | Item {item ID} does not exist in collection {collection name}. | Check that an item with the ID you're requesting exists in the collection you're querying. |
WDE0074 | WD_ITEM_ALREADY_EXISTS | An item with the requested ID value already exists. This error occurs when you try to insert an item into a collection with an _id value that already exists in that collection. If you are trying to either insert a new item or update it if it already exists, use save() . |
WDE0075 | WD_BAD_REQUEST | This error occurs when you make an invalid request using the aggregate() function. See the API reference for details on building the WixDataAggregate objects used with this function. |
WDE0076 | Validation error. {error message from Wix app collection or external database} | A request to a Wix app collection or an external database that you're working with returned with an error. Check that the data requests in your code are valid. |
WDE0077 | 'limit' cannot exceed {maximum query limit} | The query limit you provided is greater than the maximum supported by the collection. Provide a lower value. |
WDE0078 | Hook error. | The code for one of your data hook functions threw an error. For example, consider an afterInsert data hook function in a backend/data.js file that includes this line of code: throw new Error("sample error message") Once you define this hook, calling the insert() function results in the WDE0078 error. |
WDE0079 | {your collection name} is a single item collection and item must have id {expected ID}, but got {received ID} instead. | The item in a single item collection has a fixed _id value. Check that you aren't trying to change this value in your code. You can find the item's _id value using the CMS or by using find() without any filters. |
WDE0080 | { Multiple possible values.} | This error occurs when you make an API call with invalid arguments. For example, if you use the query() function without providing a collection name as an argument. To resolve this error, check the API reference to make sure you're providing the right arguments in your code. |
WDE0091 | Database quota exceeded. Delete some data and try again. | Your site has exceeded the collection storage quota. Learn more about this quota and what you can do to resolve this issue. |
WDE0092 | Dataset is too large to sort. | The data you tried to sort didn't fit into memory. This usually occurs when large items are being sorted or there are too many items being sorted to fit into memory at once. Add an index to your collection to avoid using up memory. |
WDE0093 | Invalid filter for _publishStatus field, only .eq and .ne filters are allowed with 'DRAFT' and 'PUBLISHED' possible values. | When you enable the Draft and Publish Items feature for a collection, a _publishStatus field is added to every item in that collection. If you want to filter a data request based on this field, you can only use the eq() and ne() functions. The only valid values for _publishedStatus are 'DRAFT' and 'PUBLISHED' . Check that your code isn't using other filter functions or values with _publishedStatus . |
WDE0094 | Invalid {operator} parameter. {operator} parameter must be non-empty string. | The argument passed to this function must be a non-empty string. |
WDE0109 | Payload is too large. | The request is too big. Consider restructuring your data. If you are attempting to store a media file, consider using the Wix Media API. |
WDE0110 | WD_BAD_REQUEST. | System error. Please try running your code again. |
WDE0111 | GridAppId must be provided in SANDBOX segment | To resolve this error, reload your site in the browser. |
WDE0115 | WD_UNKNOWN_ERROR | Your external database requested an unsupported data operation. |
WDE0116 | WD_UNKNOWN_ERROR | Your external database responded to Wix with an error. |
WDE0117 | MetaSiteId can not be resolved. | System error. Please try running your code again. |
WDE0118 | GridAppId {app ID} not found in instance {instance ID}. | Request provided an invalid gridAppId. To resolve this error, reload your site in the browser. |
WDE0120 | {your collection name} does not support {function name} operation. | Some specialized collections, like the ones that hold data for Wix apps, don't support the full data API. This error occurs when you try to call a function that isn't supported by a specific collection. Remove the unsupported function call from your code. |
WDE0121 | Sorting by multiple array fields is not supported | If there are multiple fields in your collection that contain arrays, you can't sort by both of them at once. For example, consider a collection item that includes a field called A whose value is [1,2,3] and a field called B whose value is [3,2,1] . In this case, attempting to sort by both A and B at once results in an error. If your collection contains multiple fields that are arrays, check that you aren't trying to sort using more than one at once. |
WDE0123 | Duplicated values cannot be added to a field with a unique index. | When you add a unique index to a collection, each value for the indexed field in that collection must be unique. This error occurs when you try to add a duplicate value for the field. To resolve the error, use a unique value. |
WDE0128 | WD_UNKNOWN_ERROR | Your external database adaptor tried to create a collection item with no _id field. Check that any item created by an external adaptor contains this field. |
WDE0131 | External database connection '{namespace}' does not exist. | This external database connection does not exist. Learn more about integrating external collections with your Wix site. |
WDE0133 | Document field is too large to index, exceeds 1024 bytes. | This error occurs when you try to add a value to an indexed field that, together with other indexed fields, becomes too large. The total size of all indexed field values per item must be 1024 bytes or less. Learn more about working with indexes in your collections. |
WDE0134 | Field names with dollar ($) prefix are not allowed. | This error occurs when you try to add a field to a collection with a $ at the beginning of its name. To resolve this error, remove the $ from the name. |
WDE0144 | Issue with processing data. | You don't have permission to perform this action. Ask the collection administrator for the required permissions. |
WDE0149 | Internal application error. | This error occurs when a Wix app collection fails with a system or unrecognized error. To resolve the error, retry the request. If the request fails, contact support. |
WDE0150 | Data hook syntax error. | This error occurs when your data.js file, or any other file it imports from, contains a JavaScript syntax error. To resolve this error, fix syntax errors in the JavaScript codebase. |
WDE0151 | Incorrect cursor provided. | Pagination error occurred: the query's cursor paging property contains an invalid cursor. Query the collection again to create a new cursor. |
WDE0152 | Cursor is expired. | Pagination error occurred: the query's cursor paging property contains an expired cursor. Query the collection again to create a new cursor. |
WDE0153 | Reference {property in referencing collection} from {referencing item id} to {referenced item id} does not exist. | You are attempting to remove a multi-reference that does not exist. Check that the reference is correct. |
WDE0154 | The data collection share policy with ID {id} was not found. | A data sharing error occurred. Learn more about sharing collections across sites. |
WDE0155 | Data collection is already shared. | The specified data collection is already shared with this site. Learn more about sharing collections across sites. |
WDE0156 | Data collection {collection name} is not shared. | The specified collection is not shared with this site. Learn more about sharing collections across sites. |
WDE0157 | Field {property name} cannot be translated as {field type} data type is not translatable. | This field cannot be translated because its type is not supported by Wix Multilingual. For example, field types such as Video and Number cannot be marked as translatable. Learn more about how Wix Multilingual works with the CMS. |
WDE0158 | Multilingual plugin must have at least one translatable field. | To enable Wix Multilingual, mark at least one field as translatable. Learn more about translation eligibility requirements for collections. |
WDE0159 | Invalid query on {collection name}. There is no prev page. | You are viewing the first page of results and cannot call prev() . If necessary, try running a different query. |
WDE0160 | Index already exists as a system index. | The field you are attempting to index is a system field for which Wix Data already has an index. |
WDE0161 | Data collection {collection name} is not multilingual. | You are querying translated content, but the collection is not translatable. Add this collection to Wix Multilingual, or select a translatable collection. Learn more about translating CMS collection content. |
WDE0162 | Language {language} is not enabled for data collection {collection name}. | The requested language is not available for this collection. Enable this language in Wix Multilingual. Learn more about managing languages in a multilingual site. |
WDE0163 | Invalid value for the page link {field name}: {cause for error}. | The value of this Page Link field does not conform to the dynamic URL slug structure. Learn more about URL slug structures. |
WDE0164 | The index {index name} with the same fields already exists in collection {collection id}. | An index already exists in this collection for the same fields. To create another index, select different fields. |
WDE0165 | Invalid query on {collection name}. There is no next page. | You are viewing the last page of results and cannot call next() . If necessary, try running a different query. |
WDE0167 | Aggregation item field name cannot end with . | Cannot apply aggregation to a field that ends with a dot character . . Change the field name or select another field to aggregate. |
WDE0168 | Document nesting level is too deep | A data item can contain up to 50 levels of nesting. Restructure the item to contain 50 nested levels or less. |
WDE0169 | Filter nesting level is too deep | A filter can contain up to 50 levels of nesting. Restructure your filter to contain 50 nested levels or less. |
WDE0170 | Data collection change is not supported. | This external collection does not support this change. Check the external database's documentation to learn what modifications it supports. |
WDE0171 | Application not installed to access the {collection id} collection | The collection you are attempting to query was created by a Wix app, but that app is no longer installed on your site. |
WDE0172 | Data hook execution throttled. | The data hook was blocked due to built-in request limitations. Learn more about backend requests in Velo. |
WDE0173 | Aggregation item field name cannot be empty. | Cannot apply aggregation to an unnamed field. Learn more about working with aggregations. |
WDE0174 | Multilingual is not supported in a Sandbox environment. | Sandbox collections do not support translated content. To view translated content, use Wix Multilingual on Live collections. |
WDE0175 | Updates to translatable collections are not supported in the non-primary language {language}. | When viewed in a non-primary language, translatable collections do not allow inserting or updating items. Only updates to non-translatable collections are allowed when viewing in a non-primary language. |
WDE0176 | Inserting data to index with multiple array fields is not supported. | When two or more arrays are included in a collection index, they cannot accept new items. |
WDE0177 | The current user does not have permissions to {action} in Sandbox environment on the {collectionName} collection. | The current user does not have sufficient permissions to perform this action in the collection's sandbox environment. Learn more about CMS collection permissions. |
WDE0178 | Invalid document revision. | Error encountered while updating the item. Try calling the method again. |
WDE0179 | Sandbox environment is disabled. | The collection's sandbox environment is disabled. |
WDE0180 | Response payload is too large. | The response payload too large. Try again, or modify your request to retrieve a smaller response. |
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:
function aggregate(collectionId: string): WixDataAggregate;
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.
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;
});
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:
_id
property value is set to null
or an empty string, an error is thrown.bulkInsert()
function is not supported for Single Item Collections.bulkInsert()
function does not support multi-reference fields. For multi-reference fields, use insertReference()
.bulkInsert()
will fail and issue an error.function bulkInsert(
collectionId: string,
items: Array<object>,
options: WixDataOptions,
): Promise<WixDataBulkResult>;
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.
The items to add.
An object containing options to use when processing this operation.
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"
* ]
*/
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.
function bulkRemove(
collectionId: string,
itemIds: Array<string>,
options: WixDataOptions,
): Promise<WixDataBulkRemoveResult>;
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.
IDs of the items to remove.
The array must contain at least one item. Passing an empty array returns an error.
An object containing options to use when processing this operation.
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"
* ]
*/
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.
_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._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:
_id
property value is set to null
or an empty string, an error is thrown.bulkSave()
function is not supported for Single Item Collections.bulkSave()
function does not support multi-reference fields. For multi-reference fields, use replaceReferences()
or insertReference()
.bulkSave()
will fail and issue an error.function bulkSave(
collectionId: string,
items: Array<object>,
options: WixDataOptions,
): Promise<WixDataBulkResult>;
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.
The items to insert or update.
The array must contain at least one item. Passing an empty array returns an error.
An object containing options to use when processing this operation.
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"
* ]
*/
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:
bulkUpdate()
function is not supported for Single Item Collections.bulkUpdate()
function does not support multi-reference fields. For multi-reference fields, use replaceReferences()
or insertReference()
.bulkUpdate()
will fail and issue an error.function bulkUpdate(
collectionId: string,
items: Array<object>,
options: WixDataOptions,
): Promise<WixDataBulkResult>;
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.
The items to update.
The array must contain at least one item. Passing an empty array returns an error.
An object containing options to use when processing this operation.
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;
});
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.
function filter(): WixDataFilter;
import wixData from "wix-data";
// ...
$w("#myDataset").setFilter(
wixData.filter().startsWith("lastName", "D").ge("age", "21"),
);
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:
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.itemId
is required to retrieve an item even from a single-item collection.function get(
collectionId: string,
itemId: string,
options: WixDataOptions,
): Promise<object>;
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.
The ID of the item to retrieve.
An object containing options to use when processing this operation.
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"
* }
*/
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:
_id
property value is set to null
or an empty string, an error is thrown._id
is pre-inserted into the collection. Single Item Collections may contain only one item.insert()
function will not run. To update or change an item in a Single Item Collection see the update()
and save()
functions.insert()
function does not support multi-reference fields. For multi-reference fields, use insertReference()
.insert()
will fail and issue an error.function insert(
collectionId: string,
item: object,
options: WixDataOptions,
): Promise<object>;
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.
The item to add.
An object containing options to use when processing this operation.
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"
* }
*/
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:
insertReference()
function only applies to multi-reference fields.insertReference()
function is not supported for Single Item Collections.function insertReference(
collectionId: string,
propertyName: string,
referringItem: union,
referencedItem: union,
options: WixDataOptions,
): Promise<void>;
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.
The property to insert the reference into.
The referring item or referring item's ID.
The referenced item, referenced item's ID, an array of referenced items, or an array of referenced item IDs.
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.
import wixData from "wix-data";
// ...
wixData
.insertReference("movies", "actors", "00001", "12345")
.then(() => {
console.log("Reference inserted");
})
.catch((error) => {
console.log(error);
});
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.
function isReferenced(
collectionId: string,
propertyName: string,
referringItem: union,
referencedItem: union,
options: WixDataOptions,
): Promise<boolean>;
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.
The property that possibly contains the references to the referenced item.
The referring item or referring item's ID.
The referenced item or referenced item's ID.
An object containing options to use when processing this operation.
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;
});
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:
skip
: 0
limit
: 50
descending
: by _createdDate
include
: noneThe 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:
Notes:
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]https://dev.wix.com/docs/velo/api-reference/wix-data/introduction#api-reference_wix-data_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.function query(collectionId: string): WixDataQuery;
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.
import wixData from "wix-data";
// ...
let query = wixData.query("myCollection");
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:
queryReferenced()
function does not trigger any hooks.queryReferenced()
function with multiple-item reference fields, and not with single-item (regular) reference fields.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.
function queryReferenced(
collectionId: string,
item: union,
propertyName: string,
options: WixDataQueryReferencedOptions,
): Promise<WixDataQueryReferencedResult>;
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.
The referring item or referring item's ID.
The property that contains the references to the referenced items.
An object for controlling the order of the returned 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) {
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"
* }
*/
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:
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.function remove(
collectionId: string,
itemId: string,
options: WixDataOptions,
): Promise<object>;
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.
The ID of the item to remove.
An object containing options to use when processing this operation.
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"
* }
*/
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.
function removeReference(
collectionId: string,
propertyName: string,
referringItem: union,
referencedItem: union,
options: WixDataOptions,
): Promise<void>;
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.
The property to remove the reference from.
The referring item or referring item's ID.
The referenced item, referenced item's ID, an array of referenced items, or an array of referenced item IDs.
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.
import wixData from "wix-data";
// ...
wixData
.removeReference("movies", "actors", "00001", "12345")
.then(() => {
console.log("Reference removed");
})
.catch((error) => {
console.log(error);
});
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.
function replaceReferences(
collectionId: string,
propertyName: string,
referringItem: union,
referencedItem: union,
options: WixDataOptions,
): Promise<void>;
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.
The property to replaces the references in.
The referring item or referring item's ID.
The referenced item, referenced item's ID, an array of referenced items, or an array of referenced item IDs.
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.
import wixData from "wix-data";
// ...
wixData
.replaceReferences("movies", "actors", "00001", "12345")
.then(() => {
console.log("References replaced");
})
.catch((error) => {
console.log(error);
});
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:
_id
property value is set to null
or an empty string, an error is thrown.save()
function does not support multi-reference fields. For multi-reference fields, use insertReference()
or replaceReferences()
save()
will fail and issue an error.function save(
collectionId: string,
item: object,
options: WixDataOptions,
): Promise<object>;
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.
The item to insert or update.
An object containing options to use when processing this operation.
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"
* }
*/
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.
function sort(): WixDataSort;
import wixData from "wix-data";
// ...
$w("#myDataset").setSort(
wixData.sort().ascending("lastName").descending("age"),
);
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:
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.
function truncate(
collectionId: string,
options: WixDataOptions,
): Promise<object>;
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.
An object containing options you can use when calling this function.
import wixData from "wix-data";
// ...
wixData
.truncate("myCollection")
.then(() => {
console.log("All items removed");
})
.catch((err) => {
console.log(err);
});
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:
_id
property that already exists in the collection.update()
function does not support multi-reference fields. For multi-reference fields, use replaceReferences()
or insertReference()
.update()
will fail and issue an error.function update(
collectionId: string,
item: object,
options: WixDataOptions,
): Promise<object>;
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.
The item to update.
An object containing options to use when processing this operation.
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"
* }
*/