How to make the wix database items unique

In my Wix website, I created a database and the field named “giaCode” should be unique.

The problem is the Wix database doesn’t have any function to keep the items which are unique – like the foreign key.

So I decided to make a function to search and delete any duplicate items in the database. But it doesn’t work.

The process should be:

  1. Import the CSV file to the database
  2. Check all rows and record it’s “_id” to the array
  3. call the array to remove the rows

The Wix code (data.js) is below:

import wixData from 'wix-data';

let n,i,j,duplicateData,items;
let k = 0;

wixData.query("Diamond")
  .count()
  .then( (num) => {
    n = num;
});

wixData.query("Customer")
  .find()
  .then( (data) => {
    items = data.items;
 });

export function checkDuplicates(value, info) {
    for (i = 0; i < n; i++) { 
        for (j = 0; i < n; j++) { 
            wixData.query("myCollection")
            .eq("giaCode", items[i].giaCode)
            .find()
            .then ((DupResults) => {
                duplicateData[k][j] = DupResults.items;
                k++;
            });
        }
    }

    for (i = 0; i < k; i++) { 
        for (j = 1; j < duplicateData[k][j].giaCode.length; j++) {
            wixData.remove("Diamond", duplicateData[i][j].giaCode)
        }
    }
}


export function Diamond_afterInsert(item, context) {
    checkDuplicates()
}

It should be work but I get the error message:
enter image description here

1 thought on “How to make the wix database items unique”

Leave a Comment