Example: No Database Duplicates

#Example #Database #Hooks #beforeInsert #dataset


The example doesn’t allow duplicates, hence only one beer. :disappointed:

Demonstrates

Note: you will find the code in the file data.js under the Backend folder:

6 Likes

Would it be possible to have the code?

Open the project in your editor from the link in the original post: Open the Example template in the Wix Editor . You will find all of the code there.

Sorry, but I don’t understand. Please explain what isn’t working for you.

I want to say that I found the code, but copying it to my other site I can not make it work.

I’m using this code but it is not working.
Could you help me?

Code:

import wixData from ‘wix-data’;

export function searchForDuplicates(value, info) {
return wixData.query(info.MembersPublic)
.eq(“userName”, value.names)
.find()
.then((results) => {
return results.items.length;
})
. catch ((err) => {
let errorMsg = err;
})
}

export function MembersPublic_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.
return searchForDuplicates(item, context).then((res) => {
if (res > 0) {
return Promise.reject(‘This item already exists’);
}
return item;
});
}

$w.onReady( function () {
$w(“#submitDataset”).onAfterSave(() => {
$w(‘#displayDataset’).refresh(); // refresh list after new item saved
});
});

?

@Matteo - if your collection Field Key is userName , then you need to use that for value as well:

.eq("userName", value.userName) 

You need to adapt the code for your own use. Collection fields, component IDs, etc need to be changed to what your site is using.

Thanks, I managed to resolve the problem.

Hello Yisrael and Matteo

I followed your example code in order to prevent duplicate in my collection field (Title). But it doesn’t work. I don’t know what wrong with tha code even if i follow step by step coding. Please have a look on it. My Field Key is “title”

import wixData from ‘wix-data’;

export function searchForDuplicates(value, info) {
return wixData.query(info.Annonceurs)
.eq(“title”, value.title)
.find()
.then((results) => {
return results.items.length;
})
. catch ((err) => {
let errorMsg = err;
})
}

export function Annonceurs_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.
return searchForDuplicates(item, context).then((res) => {
if (res > 0) {
return Promise.reject(‘This item already exists’);
}
return item;
});
}

For the second part of coding i delete repeater line cause i don’t need it at all.

import wixData from ‘wix-data’;

$w.onReady( function () {
$w(“#datasetA”).onAfterSave(() => {
});
});


In summerise collectionName = Annonceurs, or not ? In your case, collectionName is different to noDuplicationDB.

Sincerely,

The beforeInsert function uses the name of the collection as a way to create the hook. The searchForDuplicates function can be used for hooks from different collections by using the collectionName property of the context object which is passed in the info parameter.

In the example, wixData.query uses info.collectionName which is equal to “noDuplicatesDB”.

Instead of this:
return wixData.query(info.Annonceurs)

You should do this:
return wixData.query(info.collectionName)
or
return wixData.query(“Annonceurs”)

Using info.collectionName allows you to use the searchForDuplicates function for multiple collections.

I hope this helps,

Yisrael

Thanks Yisrael, the code works as well. But, the message “this value already exists” doesn’t appear when the user request failed.

How may i fixe it?

Maxwell,

I’m sorry, but I don’t understand your problem. If you are having a problem, you need to carefully check the example code.

A full tested and working example template is available to load into your editor. You can modify the code for your own use.

Yisrael

Works like a charm, Thanks Yisrael !

Hey Yisrael!

Thank you very much, it’s working really well to me but I wonder if I could use it for two different fields.

My code right now is:

import wixData from 'wix-data';
import wixUsers from 'wix-users';

export function searchForDuplicates(value, info) {
 // info contains the hook context
 // use the collectionName property to use function for multiple collections
 return wixData.query("Company")
        .eq("email", value.email)
        .find()
        .then((results) => {
 return results.items.length;
        })
        .catch((err) => {
 let errorMsg = err;
        })
}


export function Company_beforeUpdate(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(item, context).then((res) => {
 if(res > 0) {
 return Promise.reject('This item already exists');
        }
 return item;
    });
}

Should I do a searchForDuplicates2 or what could I do? I need that their Company Names are not duplicated neither…

Thank you very much!

You can either put two queries in the the searchForDuplicates() function, or create a searchForDuplicates2() function for the other check. Call them both from the beforeUpdate() hook. Make sure you handle the promises correctly.

Hi Yisrael,

I’m no able to make it work.

I have 2 questions:

  1. Do you see something wrong? I’m doing everything that you say and it’s not working. I think I don’t get what you say about promises. I connect the buttons with the Submit and the Delete options, not coding.
import wixLocation from 'wix-location';
import wixData from 'wix-data';

export function searchForDuplicates(value, info) {
 // info contains the hook context
 // use the collectionName property to use function for multiple collections
 return wixData.query("Company")
        .eq("companyName", value.companyName)
        .find()
        .then((results) => {
 return results.items.length;
        })
        .catch((err) => {
 let errorMsg = err;
        })
}

export function Company_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(item, context).then((res) => {
 if(res > 0) {
 
 return Promise.reject('This item already exists');
        }
 return item;
    });
}

export function Company_afterRemove(item, context) {
    wixLocation.to("www.weaallgopr.com")
}

I tried return wixData.query(“Company”) and
return wixData.query(info.collectionName).

The second problem is…

  1. I want a hook to redirect to the homepage (imagine the web is weaallgopr.com) after deleting the profile.

Thank you very much :frowning:

And I forgot to say that I’m working with a Read & Edit database, that’s why I use a lot of times beforeUpdate. But with beforeInsert is not working neither! >.<

Thank you for this code!!! I was able to create a tutorial video using an example of this code!!!

I am not sure if it will help anyone that is having trouble. I used it to check for duplicates when a member creates/updates a username in their profile page.

I will leave it here just in case!

Link: Create Member Website with Different Types of Members - Build Profile Page - YouTube

hahaha i follow u on youtube. It’s still not working for me… I have exactly the same but instead of beforeInsert, beforeUpdate