banner



How To Import And Export Collection Data Using The Wix-data Api

What is the wix-information Module?

Sometimes information technology's necessary (or preferential) to manage Wix collection data with code, in the involvement of saving time and gaining more functionality. The wix-data module is a group of functions that can be used to complete most any task related to managing data in a collection. Here are a few common ways of working with a drove:

  • Inserting data.
  • Getting/Retrieving data.
  • Updating an item.
  • Querying through data.
  • Filtering information.
  • Accumulation information.

The wix-data module can be used on the frontend or the backend. The focus in this article will exist using wix-data on the backend, and calling the functions from the frontend.

Setting up

Allow'southward say y'all've decided to beginning recording every animal you see. Every. Unmarried. I. Their names, their habitat, their species, you lot want all that data! This calls for a database collection!

Wix-data Module Animals Collection

Here is a new drove named "Animals", with 3 text fields:

  • Name
  • Species
  • Habitat

To work with the new collection, a new spider web module must be created.

Wix-data Module Backend File

Recall that web modules use the .jsw extension. This one is called dataFunctions.jsw.

With the collection and the spider web module in place, you lot're ready to explore some of the capabilities of the wix-information module. A skilful place to start is the .insert() method!

Insert Data with wix-data via the Backend

The .insert() method adds an item to a collection. It has 2 parameters:

  • A string with the collection ID of the collection you want to add to.
  • An object that contains the data you lot want to add.
          
            

import wixData from 'wix-data' ;

consign office addAnimal ( animal ) {

wixData . insert ( 'Animals' , animal )

. then ( ( result ) => {

console . log ( result ) ;

console . log ( ` ${ animal . name } has been added ` ) ;

} )

. catch ( ( err ) => {

panel . log ( err ) ;

} ) ;

}

Breaking downwards the code into chunks helps to show what's going on:

  • Offset you lot need to import wixData from the wix-data module to proceeds access to all of the functionality in the wix-data module.
  • consign function addAnimal() creates and exports the function to enable its utilise on the frontend.
  • The wixData.insert('Animals', item) method call takes a two arguments, a cord of the collection name and the item to be inserted into our collection.
  • .insert() is asynchronous, it returns a Promise which calls for .then() and .catch() to be chained later on.
  • Inside of .then()'s callback part, there are two console.log()'south which volition run when the Promise resolves successfully. One is to print out the new object that was stored, and the other is a confirmation message.
  • The .grab() logs an error to the panel if the Hope is rejected. This could happen due to permissions problems, or items having conflicting/identical ID'southward. It's important to annotation that .insert() tin can only add new items to a collection, information technology cannot overwrite any existing items. In either case, if the .catch() method is called, and so the insertion did not occur.

Calling the Function

The addAnimal() function is now set up to be chosen in the frontend.

          
            

import { addAnimal } from 'backend/dataFunctions' ;

permit newAnimal = {

'proper noun' : 'Rex' ,

'species' : 'dog' ,

'habitat' : 'home'

} ;

addAnimal ( newAnimal ) ;

The code higher up:

  • imports the addAnimal() function from dataFunctions.jsw into the frontend.
  • ThenewAnimal object is the item beingness inserted into the collection. Information technology has belongings-value pairs, where the property is the name of the drove field, and the value is the term to be inserted. Information technology's important that the value matches the field type.
  • Calling addAnimal(newAnimal) adds the newAnimal item into the 'Animals' collection.

Previewing the page will run the code. Inside the Wix developer panel, you will see the two logs from the dataFunctions.jsw file.

Wix-data Module Insert Output

You may find how the results object log shows four properties and values that yous didn't have in your newAnimal object:

  • _id
  • _owner
  • _createdDate
  • _updatedDate

These are automatically created by the .insert() method when the item is added to the drove.

If you ever want to check that an item has been inserted correctly, check the collection via the Database tab.

Wix-data Module Updated Animals Collection

Notice how Rex has been added to the list, and given a unique ID.

Getting Information

Retrieving an particular from a drove is done by using the .get() method. .get() takes has 2 arguments:

  • A cord with the drove ID from the drove yous desire to add to, just like in the .insert() method.
  • A string with the ID of the item y'all are retrieving. Each item in your collection has a unique ID generated by Wix, or past the user.
          
            

import wixData from 'wix-data' ;

export part getAnimal ( itemId ) {

wixData . get ( 'Animals' , itemId )

. and then ( ( issue ) => {

console . log ( result ) ;

} )

. catch ( ( err ) => {

console . log ( err ) ;

} ) ;

Most of this should look familiar to you. The key deviation is that .get() returns a Promise that resolves to the particular with the detail'due south ID that you lot pass in (or null if the item is not found). The Hope is rejected if the electric current user does not have read permissions for the collection.

Calling the Role

With the function set upwards in the backend, it'south ready to be called in the frontend.

          
            

import { getAnimal } from 'backend/dataFunctions' ;

let itemId = 'a239357e-a00e-400e-a02a-789b36517c0e' ;

getAnimal ( itemId ) ;

This code:

  • imports the getAnimal() function from dataFunctions.jsw into the frontend.
  • itemId stores the ID of the particular you want to get from the collection, using the string from the _id field of the collection. For this example, we are difficult coding the variable, only in practice, at that place are many different ways to programmatically get the ID of an item. For case, using .getCurrentItem(), or getting it later on using .insert().
  • Calls getAnimal(itemId) gets the animal with the specific ID from the 'Animals' drove.

Only like before, previewing the page will run the code. With the Wix developer panel open, you will see the requested item object logged out!

Wix-data Module Get Output

Querying

The .query() method requests data from a collection past searching for specific details nearly an item. It takes a unmarried statement, the drove ID of the collection you would like to get data from.

          
            

import wixData from 'wix-data' ;

export office queryAnimals ( ) {

wixData . query ( 'Animals' )

. find ( )

. so ( ( results ) => {

console . log ( results ) ;

} )

. catch ( ( err ) => {

panel . log ( err ) ;

} ) ;

}

In its most simple grade:

  • A .query() method is attached to wixData to build the query.
  • A .discover() is chained to .query() to render the items that match the query.
  • And since .find() returns a Promise, a .and then() callback office is used, which contains the code to display the resolved hope, or catch any errors.

Calling the Function

          
            

import { queryAnimals } from 'backend/dataFunctions' ;

queryAnimals ( ) ;

On the frontend:

  • import the function from dataFunctions.jsw.
  • telephone call the queryAnimals(collectionId) role.

Wix-data Module Query Output

When a successful Promise is returned, all of the items found in the collection are returned inside of a WixDataQueryResult object. The .limit() method controls how many results are returned per folio, and results pages tin can exist navigated with .prev() and .side by side.

The WixDataQueryResult object above contains:

  • An .items property that holds an array of all the items.
  • A .length property, showing the number of items in the current results page, defined by the .limit()] method (which has a default value of 50).
  • A .totalCount property, showing the full number of items that match the query, regardless of page.
  • And a .query property that holds a wixDataQuery object of the query used to get the electric current results.

Refining The Query

Between .query() and .find() is the opportunity to narrow downward the search. One common case is .eq() because it allows yous to find items in your collection that equal your specified parameters. The .eq() method takes two arguments:

  • a field key, equally a string.
  • and a search term, equally a cord.
          
            

import wixData from 'wix-information' ;

export function querySpecificAnimals ( fieldKey , species ) {

wixData . query ( 'Animals' )

. eq ( fieldKey , species )

. discover ( )

. then ( ( results ) => {

console . log ( results . items ) ;

} )

. catch ( ( error ) => {

panel . log ( error ) ;

} ) ;

}

Observe that the function querySpecificAnimals() has two parameters fieldKey and species. These parameters are used the .eq(fieldKey, species) line. Later, when you call this office in the frontend, you lot tin specify the field key of the 'Animals' collection and the name of the species too. In the log statement of .then()'due south callback office, .items is chained to results to only get the items from the WixDataQueryResult object.

Calling the Function

          
            

import { queryAnimals } from 'backend/dataFunctions' ;

querySpecificAnimals ( 'species' , 'dog' ) ;

Calling the role on the frontend is the same, no matter how many refinement methods you add!

Wix-data Module Refined Query Output

When successful, an array containing only the items matching the criteria set past .eq() is returned.

To narrow down the results fifty-fifty further, try chaining some additional methods, such as .gt(), .hasSome(), or .startsWith(), and call the function to run into the results.

Aggregating Data

Counting, comparing, and performing calculations on collections, or groups within collections, can be done using the .aggregate() method. Information technology has a single parameter: the collection ID of the collection y'all would similar to get information from.

.aggregate() returns a WixDataAggregate object, and uses the .run() method. 1 of import thing to notation is that .aggregate() can be used on whatever collection y'all create from scratch, simply not on Wix App Collections.

          
            

import wixData from 'wix-data' ;

export role totalAnimalsAggregate ( ) {

wixData . aggregate ( 'Animals' )

. count ( )

. run ( )

. and so ( ( results ) => {

console . log ( results )

} )

. catch ( ( error ) => {

panel . log ( mistake )

} ) ;

}

The .aggregate() syntax should expect familiar, in that chaining various methods allows you to refine the results. In the code higher up, .count() is placed in betwixt .amass() and .run() to simply count the total number of items in the collection. To run more intricate aggregations, methods like .avg(), .min(), .max(), and .sum() tin be used to give you exactly what y'all're looking for.

Calling the Role

          
            

import { totalAnimalsAggregate } from 'backend/dataFunctions' ;

totalAnimalsAggregate ( )

Calling the function on the frontend is the same as when querying data. Just import the function and call it.

Wix-data Module Aggregate Output

.run() returns a Hope that resolves to a WixDataAggregateResult object. Inside the object, within the ._items holding array, .count reveals the full number of items in the drove.

Epitomize

Wix provides a lot of functionality for working with data, and this article simply scratches the surface. You now know how to use lawmaking to:

  • add data to a collection.
  • get a specific detail from a collection.
  • create a nuanced query for more items in a drove.
  • run an assemblage on a collection

With this newly gained knowledge, yous tin begin implementing the wix-data module into your code. Try out some of the methods you learned here, as well equally some others from the API reference. And if y'all're looking to take wix-information even further, endeavour adding hooks to complete other tasks alongside data-managing operations you've already learned. All of these tools can be used to greatly streamline and enhance information usage on your site!

How To Import And Export Collection Data Using The Wix-data Api,

Source: https://www.codecademy.com/article/wix-data-module

Posted by: brownthabould.blogspot.com

0 Response to "How To Import And Export Collection Data Using The Wix-data Api"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel