Wix Data Module

Codecademy Team
Managing data is quick and easy with database collections built right into the Editor. For even more customization, the wix-data module gives you greater functionality for manipulating, and querying data.

What is the wix-data Module?

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

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

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

Setting up

Let’s say you’ve decided to start recording every animal you see. Every. Single. One. Their names, their habitat, their species, you want all that data! This calls for a database collection!

Wix-data Module Animals Collection

Here is a new collection named “Animals”, with 3 text fields:

  • Name
  • Species
  • Habitat

To work with the new collection, a new 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 web module in place, you’re ready to explore some of the capabilities of the wix-data module. A good 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 two parameters:

  • A string with the collection ID of the collection you want to add to.
  • An object that contains the data you want to add.
import wixData from 'wix-data';
export function addAnimal(animal){
wixData.insert('Animals', animal)
.then((result) => {
console.log(result);
console.log(`${animal.name} has been added`);
})
.catch((err) => {
console.log(err);
});
}

Breaking down the code into chunks helps to show what’s going on:

  • First you need to import wixData from the wix-data module to gain access to all of the functionality in the wix-data module.
  • export function addAnimal() creates and exports the function to enable its use on the frontend.
  • The wixData.insert('Animals', item) method call takes a two arguments, a string 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 afterward.
  • Inside of .then()‘s callback function, there are two console.log()‘s which will 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 .catch() logs an error to the console if the Promise is rejected. This could happen due to permissions issues, or items having conflicting/identical ID’s. It’s important to note that .insert() can only add new items to a collection, it cannot overwrite any existing items. In either case, if the .catch() method is called, then the insertion did not occur.

Calling the Function

The addAnimal() function is now ready to be called in the frontend.

import { addAnimal } from 'backend/dataFunctions';
let newAnimal = {
'name': 'Rex',
'species': 'dog',
'habitat': 'home'
};
addAnimal(newAnimal);

The code above:

  • imports the addAnimal() function from dataFunctions.jsw into the frontend.
  • ThenewAnimal object is the item being inserted into the collection. It has property-value pairs, where the property is the name of the collection field, and the value is the term to be inserted. It’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 console, you will see the two logs from the dataFunctions.jsw file.

Wix-data Module Insert Output

You may notice how the results object log shows four properties and values that you 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 collection.

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 Data

Retrieving an item from a collection is done by using the .get() method. .get() takes has two arguments:

  • A string with the collection ID from the collection you want to add to, just like in the .insert() method.
  • A string with the ID of the item you are retrieving. Each item in your collection has a unique ID generated by Wix, or by the user.
import wixData from 'wix-data';
export function getAnimal(itemId){
wixData.get('Animals', itemId)
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});

Most of this should look familiar to you. The key difference is that .get() returns a Promise that resolves to the item with the item’s ID that you pass in (or null if the item is not found). The Promise is rejected if the current user does not have read permissions for the collection.

Calling the Function

With the function set up in the backend, it’s 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 item you want to get from the collection, using the string from the _id field of the collection. For this example, we are hard coding the variable, but in practice, there are many different ways to programmatically get the ID of an item. For instance, using .getCurrentItem(), or getting it after using .insert().
  • Calls getAnimal(itemId) gets the animal with the specific ID from the 'Animals' collection.

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

Wix-data Module Get Output

Querying

The .query() method requests data from a collection by searching for specific details about an item. It takes a single argument, the collection ID of the collection you would like to get information from.

import wixData from 'wix-data';
export function queryAnimals() {
wixData.query('Animals')
.find()
.then((results) => {
console.log(results);
})
.catch((err) => {
console.log(err);
});
}

In its most simple form:

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

Calling the Function

import { queryAnimals } from 'backend/dataFunctions';
queryAnimals();

On the frontend:

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

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 page, and results pages can be navigated with .prev() and .next.

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 total 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 current results.

Refining The Query

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

  • a field key, as a string.
  • and a search term, as a string.
import wixData from 'wix-data';
export function querySpecificAnimals(fieldKey, species) {
wixData.query('Animals')
.eq(fieldKey, species)
.find()
.then((results) => {
console.log(results.items);
})
.catch((error) => {
console.log(error);
});
}

Notice that the function querySpecificAnimals() has two parameters fieldKey and species. These parameters are used the .eq(fieldKey, species) line. Later, when you call this function in the frontend, you can specify the field key of the 'Animals' collection and the name of the species as well. In the log statement of .then()‘s callback function, .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 function 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 by .eq() is returned.

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

Aggregating Data

Counting, comparing, and performing calculations on collections, or groups within collections, can be done using the .aggregate() method. It has a single parameter: the collection ID of the collection you would like to get information from.

.aggregate() returns a WixDataAggregate object, and uses the .run() method. One important thing to note is that .aggregate() can be used on any collection you create from scratch, but not on Wix App Collections.

import wixData from 'wix-data';
export function totalAnimalsAggregate() {
wixData.aggregate('Animals')
.count()
.run()
.then((results) => {
console.log(results)
})
.catch( (error) => {
console.log(error)
});
}

The .aggregate() syntax should look familiar, in that chaining various methods allows you to refine the results. In the code above, .count() is placed in between .aggregate() 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() can be used to give you exactly what you’re looking for.

Calling the Function

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 Promise that resolves to a WixDataAggregateResult object. Inside the object, within the ._items property array, .count reveals the total number of items in the collection.

Recap

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

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

With this newly gained knowledge, you can begin implementing the wix-data module into your code. Try out some of the methods you learned here, as well as some others from the API reference. And if you’re looking to take wix-data even further, try 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 data usage on your site!