#Example #Database #Hooks #beforeInsert #dataset
The example doesn't allow duplicates, hence only one beer. 😞
Demonstrates
Links for this example
About this example
Using the beforeInsert() data hook, you can check if the value to be inserted already exists in the database collection. If the value exists, the insert is rejected.
Note: you will find the code in the file data.js under the Backend folder:
Hi Yisrael,
I copied your code and made changes in collection name and field I want to restrict from duplication. It worked in preview mode but it's not working on live site. Could you help me please?
Here is my code -
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 ComplimentaryPackRegistration_beforeInsert(item, context) { //TODO: write your code here... return searchForDuplicates(context.collectionName, "emailid", item).then((res) => { if(res > 0) { return Promise.reject('This item already exists'); } return item; }); }
$w.onReady(function () { $w("#dataset1").onAfterSave(() => { }); });
Hi Yisrael! I've tried everything in the comments and watched Code Queens tutorial and I'm still stuck. My current code is below. My database name is "getSubscribers" and I'm trying to stop duplicate email addresses being entered to my custom dataset form. I have tried in both preview and published form and I've submitted my own email endless times, having tried many different variations. I wasn't sure if I was putting the wrong info in to the code?
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("getSubscribers") .eq("email", value.email) .find() .then((results) => { return results.items.length; }) .catch((err) => { let errorMsg = err; }); } export function getSubscribers_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 email is already subscribed'); } return item; }); }
Any help would be fab! Thank you!!
it isn't working for me. i've done so many alterations but to no avail. either it saves all or it does not save at all; error('This client already exists') messages even with new names
//BACKEND:
import wixData from 'wix-data';
export function searchForDuplicates(PersonalLoans, value, item) {
return wixData.query("PersonalLoans")
.eq('name', value.name)
.find()
.then((results) => {
return results.items.length;
})
.catch((err) => {
let errorMsg = err;
});
}
export function PersonalLoans_beforeInsert(item, context) {
return searchForDuplicates(context.PersonalLoans, 'name', item).then((res) => {
if (res > 0) {
return Promise.reject('This client already exists');
}
return item;
});
}
//MAIN PAGE
import wixData from 'wix-data'
$w.onReady(function () {
$w("#dataset1").onAfterSave(() => {
$w('#dataset1').refresh();
});
});
Hey, i got a question about this. Since there can be multiple error in the user input, how do I make the code react to the username being incorrect specifically. For example:
I have one text element saying "Something went wrong, try again" for whenever theres some kind or error but I want a text element saying "Username is taken" to be shown specifically when the username is taken. Thanks in advance!
#database #duplicates #error
Hi, I would like to know if it's possible to instead of preventing a duplicate, it changes its data, for example :
If I type in an already registred member in the form and type different informations for them (like changing age or something), it changes it in database. It's like updating the item without using browing buttons like next or back.
I hope I made it clear, thank you.
hi, if i want to prevent duplicate on 2 fileds, for exapmle- id and description fileds. its posible?
thank youuuu! this example very help me
does this work for a custom member sign up lightbox? I have not been able to get it to work?
my database value is Handle so in this 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 }); });
would I change .eq("userName", value.names) to .eq("handle", value.names)
Hi, I am using the following code to avoid duplicate data entries, but it's only working in preview only not on the live site. Can any one explain why ? Please help me !
(Code):
import wixData from 'wix-data'; $w.onReady(function () { $w("#input3").onChange((event, $w) => { wixData.query("Qualification") .eq('title', event.target.value) .find() .then((results) => { if (results.length > 0) { //id is not unique. show error and disable submit button $w('#button1').disable(); $w('#text39').show(); } else { //id is unique. do nothing $w('#text39').hide(); } }).catch((err) => { let errorMsg = err; }); }); });
My code just works on preview? Can anyone help me solving this problem?
And yes i set the permissions right.
Thanks
Very nice example!
Thanks Yisrael,
I'm new to this API and was struggling a few hours trying to make it work given that the primary fields in the collections don't behave as primary keys.
Hi Yisrael, I am using the code that we have here as an example. However, when I test, I am still able to resubmit the same information in my form. It does not prevent me from registering twice. I am sure exactly I am missing.
As you mentioned in an earlier post, I would like to also share my URL, however you mentioned to Only authorized Wix personnel can get access to your site in the editor. How do I do that? And I am not sure about how I set up the repeater as well.
Here is what I am using: 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("CRMEVENTS") .eq("Email", value.Email) .find() .then((results) => { return results.items.length; }) .catch((err) => { let errorMsg = err; }); } export function CRMEVENTS_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; }); }
Hi, Ysrael, I know this post was written some time ago, but I too tried to insert this code into my own site, and unsurprisingly, my debugger complains about the "#saveDataset" and '#dislplayDAtatset'. Also, I see that the comments #text5 and #text6 are attached to a NoDuplicatesDB submit dataset which I cannot see in your database (I only see the NoDuplicatesDB dataset.
Hey Blai, maybe it's magic. 🙃 Glad you got it working and for sharing your code. 🍻
I tried now with the exactly same code and its working. Is it possible that it wasn't working with all the data that I uploaded before adding the code? Cause now I deleted all the data and with the new data is working fine >.<
That's the code (maybe it helps to other users)
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 searchForDuplicates2 (value, info) { // info contains the hook context // use the collectionName property to use function for multiple collections return wixData.query("TravelJobs") .eq("jobName", value.jobName) .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; }); } export function Jobs_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 searchForDuplicates2 (item, context).then((res) => { if(res > 0) { return Promise.reject('This item already exists'); } return item; }); }
export function Jobs_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 searchForDuplicates2 (item, context).then((res) => { if(res > 0) { return Promise.reject('This item already exists'); } return item; }); }
Thanks and sorry!
What isn't working? Does the data get entered? Does it find duplicates?
Because I deleted everything, I had like 50 users. Okay, let me try it again and I will show you, you will see it's not working
Blai,
You don't say what isn't working. Also, your database is empty so you won't have duplicates. You should review the code in the example and ensure that you are implementing your code correctly.
I would suggest carefully reviewing the information about Database Collections and Connecting Data. Also, refer to the information about Data hooks.
Good luck,
Yisrael