Hello, I am attempting to create code that checks for a duplicate email input into a data set. The data set ID is ‘GlideUserSignUp’, and the field ID within the data set is ‘email’. The issue is when I test this code, I am getting the error that this item already exists even though it does not. I am not sure if the code I am using is the most efficient or even correct for that matter. Any help would be much appreciated.
The following is what I have on the backend data.js:
import wixData from 'wix-data';
export function searchForDuplicates(collection, field, item) {
// info contains the hook context
// use the collectionName property to use function for multiple collections
return wixData.query(collection)
.eq(field, item[field])
.find()
.then((results) => {
return results.items.length;
})
.catch((err) => {
let errorMsg = err;
});
}
export function GlideUserSignUp_beforeInsert(item, context) {
// Calls routine to check if value already exists in the collection.
// If value not found, then save record.
// Else, if value is found, then reject this insert to prevent duplicate values.
// Note: concurrent inserts may result in duplicates.
// Pass context to searchForDuplicates to use for multiple collections.
return searchForDuplicates(context.collectionName, "emails", item).then((res) => {
if(res > 0) {
return Promise.reject('This item already exists');
}
return item;
});
}