This tutorial aims to show you how to stop duplicate entries being entered into a database.
Required Elements:
Whatever you want to restrict!
APIs Used:
Wix Data
Specific Requirements:
Before Insert Hook, or a Before Update Hook
The Code:
import wixData from 'wix-data';
export function searchForDuplicateInDatabase(value) {
return wixData.query("Database")
.eq("fieldKey", value.fieldKey)
.find()
.then((results) => {
return results.items.length;
})
.catch((err) => {
let errorMsg = err;
})
}
export function Database_beforeInsert(item, context) {
return searchForDuplicateInDatabase(item, context).then((res) => {
if(res > 0) {
return Promise.reject('This item has already been submitted to the collection!');
}
return item;
});
}
If you have a dataset on your page to insert to the collection, this will display the error message that's connected to the dataset.
Editable Features:
The Collection Name, you don't have to have your collection called "Database".
The Field Key, you don't have to have it called "fieldKey".
The rejected error that displays in the DEV Console, you can change this to something more meaningful for your project.