Velo:Wix Data と Wix Dataset API について

読了時間:8分

Visit the Velo by Wix website to onboard and continue learning.
Data is an integral part of many websites. Data refers to information your site displays or collects from site visitors. For example, real estate sites, sites with a store, and sites with a form all contain data.

Velo provides you with many ways to manage and manipulate your site data. This article provides an overview of the different data operations you can perform using Velo.
Note
Wix places quotas on data requests made by your site, as well as the amount of data your site can contain. These quotas affect the number of requests your site can make per minute and the amount of time your requests can run for.

Data Building Blocks

There are 3 components involved in managing your site's data:

  • Database collections: Where you store your site's data.
  • Datasets: An element hidden from site visitors that acts as a connector between your collection and page elements.
  • Page elements: The elements on your site that display or gather data. For example, a repeater displays data, and user inputs collect data from site visitors.

No Code Required

Before jumping into code, it's helpful to know that there are many data operations you can perform without any code. By connecting the content stored in your database collection with your page elements via a dataset, you can do the following without using any code:


Dataset plus Code

If you are using a dataset to connect your database collection content with your page elements, you can extend your dataset's built-in capabilities by adding code from the wix-dataset APIs to your site. 
The wix-dataset APIs are divided into 2 sections: 
  • Dataset: For regular datasets. 
  • DynamicDataset: For dynamic datasets, special datasets for dynamic pages that control how the  elements on your dynamic pages interact with the data in your collections. This section includes all the functions in the Dataset section, plus a couple additional functions specific to dynamic datasets.

Dataset Mode

The mode of your dataset affects which dataset functions you can call. For example, if you set your dataset mode to Read-only, you won't be able to call the save() function on your dataset, since it writes from your dataset to your collection.

Dataset onReady() Event Handler

Most wix-dataset functions run properly only if they're called after the dataset has loaded its data. 
  • If you are calling a dataset function in the page's onReady() function, you should make sure that the dataset is ready by calling the function you'd like to use from inside the dataset's onReady() function (not to be confused with the page's onReady() function mentioned above). To check whether the dataset function you are using requires onReady(), see the Velo API Reference
1$w.onReady(function () {  // Page onReady() function
2  $w("#myDataset").onReady( () => {  // Dataset onReady() function
3    console.log("The dataset is ready");
4  });
5});
  • If you're calling the dataset function outside the page's onReady() function (for example, in an event handler), you can assume the dataset has loaded it's data already. In fact you should not call the dataset function from inside the dataset's onReady() function, since if the dataset has already loaded its data, the dataset onReady() function may never run, and your code may not execute.
To summarize: Wrap your dataset function in the dataset's onReady() event handler only if the function requires that the dataset's data must be loaded first, and if the function is called inside the page's onReady() function.

Work with the Current Dataset Item

You can get and set information for the current dataset item. Examples of a current dataset item are the current item in a dynamic page, a repeater item in which a contextual event occurred (such as a button click), or the currently displayed item on a regular page with previous and next buttons.

  • getCurrentItem( ): Gets an object representing the current item of the dataset.
  • setCurrentItemIndex( ): Saves the current item in the collection, sets the current item as the item with the specified index, and updates connected page elements with the new current item's values.
  • getCurrentItemIndex( ): Gets the index of the current item in the dataset (starts from 0).
  • setFieldValue( ): Sets the value of a field in the current item. Does not save the new value in the database collection.
  • setFieldValues( ): Sets the value of multiple fields in the current item. Does not save the new values in the database collection.
  • new( ): Saves the current item and creates a new blank item immediately following the current item.

Filter and Sort Your Dataset's Data

You can apply a variety of filters to your dataset, as well as sort the dataset's data in ascending or descending order.

Update the Dataset and Database Collection

The following functions update either the dataset or database collection and synchronize the items in the collection, dataset, and page elements.
  • save( ): Saves the current dataset item in the collection and updates connected page elements with the current item's new value.
  • refresh( ): Resends collection content to the dataset and updates connected page elements.
  • revert( ): Reverts the current item to its saved state in the collection and updates connected page elements with the current item's old values.
  • remove( ): Deletes the current dataset item from the database collection and updates connected page elements with the next item's values.

Paginate

You can use dataset pagination functions to navigate dynamic pages, load more content into a repeater, get the index of the current page, and more.

A dataset's page size determines how many items are initially displayed in a repeater connected to the dataset. You can then paginate through each 'page' of the dataset, loading the next batch of items into the repeater. 

Here are the dataset functions available for pagination:
Size, Index & Count
  • setPageSize( ): Sets the dataset's page size.
  • getPageSize( ): Gets the dataset's page size.
  • getCurrentPageIndex( ): Gets the index of the current dataset page (starts from 1).
  • getTotalCount( ): Gets the total number of items in a dataset. If a filter is applied to the dataset, gets the number of items that match the filter's criteria.
  • getTotalPageCount( ): Gets the number of pages in a dataset: the number of total items divided by the page size.

Previous and Next Item
  • hasPrevious( ): Checks whether the current item is the first item in the dataset.
  • previous( ): Saves the current item and moves to the previous item in the dataset.
  • getPreviousDynamicPage( ): Gets the URL of the previous dynamic page (dynamic datasets only).
  • hasNext( ): Checks whether the current item is the last item in the dataset.
  • next( ): Saves the current item in the collection and moves to the next item in the dataset.
  • getNextDynamicPage( ): Gets the URL of the next dynamic page (dynamic datasets only).

Previous and Next Page
  • hasPreviousPage( ): Checks whether the current page is the first page in the dataset.
  • previousPage( ): Saves the current item and moves to the previous page of items.
  • hasNextPage( ): Checks whether the current page is the last page in the dataset.
  • nextPage( ): Saves the current item in the collection and moves to the next page of items.

Load Content
  • loadMore( ): Loads the next page of items in addition to the current page of items.
  • loadPage( ): Loads the specified page of the dataset.

Event Handlers: Run Code Before and After Dataset Operations

Only Code

Sometimes you might need additional functionality for your data that isn't available with datasets. Or you might find it easier to organize your data operations by handling them only with code instead of via the UI.

You can use the wix-data APIs for this purpose. The Data APIs provide you with additional functionality and customization options for managing and manipulating your site content. Here's an overview of what you can do with wix-data:

Save Content to a Collection

  • insert(): Add a new item to a collection. Will not update an existing item. Use this function when you don't want to overwrite the item if it already exists in the collection.
  • update(): Update an item in a collection. Will not add a new item if the item doesn't already exist.
  • save(): Add or update an item in a collection. If the item exists, it will update. If not, the new item is added.
  • bulkInsert(): Add multiple items to a collection.
  • bulkSave(): Add or update multiple items in a collection.
  • bulkUpdate(): Update multiple items in a collection.

Delete Content from a Collection

Get Content from a Collection and Display It on Your Site

  • get(): Retrieve a single item from a collection.
  • query(): Start a process that will retrieve 1 or more items from a collection. The process is completed when you run the find() function.

Filter and Sort Your Retrieved Data

  • WixDataQuery functions: Apply these to a query to filter or sort your retrieved data.

Limit Your Retrieved Data

  • limit(): Limit the number of items a query returns.
  • skip(): Set the number of items to skip before returning query results.

Get the Results of a Query

Once you have added filters, a sort, or limited your query, you can get the query results:

Paginate Your Query Results

You can use the WixDataQueryResult functions and properties to paginate your query results.

  • totalCount: Total number of items in the query result.
  • pageSize: The number of items in a query results page. Defined by the limit() function.
  • length: The number of items in the current page of query results. Defined by the limit() function. Identical to pageSize except for the last page of results, which depends on the remaining number of items.
  • totalPages: Total number of pages in the query result.
  • currentPage: Index of the current results page.
  • hasNext( ): Whether there is another page of query results.
  • hasPrev( ): Whether there is a previous page of query results.
  • next( ): Retrieves the next page of query results.
  • prev( ): Retrieves the previous page of query results.

You can also paginate the results of a referenced query.

Work with Collection Reference Fields

Use reference fields to connect one database collection with another database collection.

Aggregate: Perform Calculations on Collection Data

  • aggregate(): Build an aggregation. After performing calculations on your aggregation, you use the run() function to run the aggregation and return the results.
  • sum(): Calculate the sum of all values of a collection field.
  • avg(): Calculate the average value of a collection field.
  • count(): Calculate the item count of each aggregation group.
  • max(): Get the maximum value from each aggregation group.
  • min(): Get the minimum value from each aggregation group.
You can sort, filter, group, limit, or skip items in an aggregation. You can also paginate the results of an aggregation.

Hooks: Perform Actions Before or After Specific Data Operations

You can run any code you want via a hook immediately prior to or following specific data operations, such as insert(), remove(), update(), and query().

For example, let's say you wanted to perform a calculation on some data or capitalize some strings before you insert them into a database collection, you could use the beforeInsert() hook.
Notes
• If you receive a "Collection didn't load due to a syntax error" message, review your data.js file and confirm that the syntax and formatting of your hooks are correct.

• Do not use the `afterQuery()` hook to modify collection data. This can cause the Content Management System (CMS) to fail when loading. If you need to modify the results of queries before performing other data operations use the appropriate hook, such as `beforeInsert()` or `beforeUpdate()`.

お役に立ちましたか?

|