Hi, I’m trying to validate if the user name they are inserting in a form already exists to reject petition and have a clean database without duplicates. However, the code i found in the forum is not working, it just let’s me submit with any user name (including the ones that already exist. This is my code:
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 DatosClientes_beforeInsert(item, context) {
//TODO: write your code here…
// 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, “usuario”, item).then((res) => {
if (res > 0) {
return Promise.reject(‘This item already exists’);
}
return item;
});
}
Have any ideas of how can I fix it please?