Hi Anthony.
check out this code sample.
I hope it does what you meant for it to do.
import wixData from 'wix-data'
/* INSERT HOOK SAMPLE CODE - ABORT THE INSERT IF DUPS FOUND
*
* assumptions:
* 1. collection name is c1
* CHANGE THE FUNCTION NAME FROM c1_beforeInsert TO yourCollectionName_beforeInsert
*
* 2. collection has these fields: name(text), email(text), number(number)
* CHANGE THESE VALUES TO VALUES THAT MATCH YOUR RELEVANT COLLECTION FIELD NAMES!
*
* the code looks for items in the collection that have the same name or email or number.
* if it finds any - the insert is aborted
*
*/
export function c1_beforeInsert(item, context) {
//all log messages will show when we run this code.
//they will help us debug and see all is working well.
//they have no impact other than that and can be safely removed
//once we see the code is working well
console.log("in before insert hook");
console.log("name is " + item.name);
console.log("email is " + item.email);
console.log("number is " + item.number);
//create a new promise object.
//in the promise's body we'll look for dups.
//if we find any, we will reject the promise and abort the insert.
let p = new Promise(function(resolve, reject)
{
console.log("in promise body");
//create a query to look for items with the same name as the item we're tring to insert
let name_q = wixData.query("c1").eq("name", item.name);
//create a query to look for items with the same email as the item we're tring to insert
let email_q = wixData.query("c1").eq("email", item.email);
//create a query to look for items with the same number as the item we're tring to insert
let number_q = wixData.query("c1").eq("number", item.number);
//create a query to look for items with the same name OR the same number OR the same email as the item we're tring to insert
let big_q = name_q.or(email_q).or(number_q);
//run the query to count the number of items that match
big_q.count().then(count =>
{
console.log("after big_q returns");
if (count === 0)
{
console.log("count is zero, no dups found, resolving the promise to the original 'item' so the insert can proceed");
resolve(item);
}
else
{
console.log("count is more than zero, rejecting the promise with an error message");
reject("count is more than 0, dups found!");
}
});
});
//return the promise from the hook
return p;
}
Let me know if this makes any senseā¦
thanks!