Trying to make a beforeinsert unique validation for username

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?

There are two great tutorials that you can use that will help guide you in the right direction and both come with full instructions and code for it.

@yisrael-wix
This one is by Yisrael (Wix Admin) where you can open the provided link given in your own Wix Editor and be able to view the page with all the elements etc made up on the page, along with all the code setup for you in the code tabs already too.
https://www.wix.com/corvid/forum/corvid-tips-and-updates/example-no-database-duplicates

@code-queen
This other one is by Wix Expert Nayeli (Code Queen) and it also has a website that you can get the full code from and a youtube video by herself too that goes through the whole tutorial of the page with you.
https://codequeen.wixsite.com/membership-dashboard
https://www.youtube.com/watch?v=yLCOqsVHhD0

Bookmark this forum’s example page so that you can refer back to whenever needed.
https://www.wix.com/corvid/examples