Unique DB fields

I have a field in a collection which needs to be unique (data entry is done directly to the DB).
Is there any way to enforce this?

Hi Tal,

You have two ways to enforce a unique field:

  1. You can add a ‘beforeInsert’ and ‘beforeUpdate’ hooks to your collection.
    An example code for beforeInsert (you should add a similar code to beforeUpdate if needed):
import wixData from 'wix-data';

export async function test_beforeInsert(item, context) {
	const {items} = await wixData.query(context.collectionName).eq("uniqueField", item.uniqueField).find()
	
	return !items.length ? item : Promise.reject()
}

hooks documentation:

  1. You can write the same logic on the onBeforeSave event on the dataset.
    dataset onBeforeSave documentation:
    wix-dataset - Velo API Reference - Wix.com

Enjoy coding :slight_smile:

Hi Mor.
Thank for your response.
Do these hooks run also when adding or editing DB entries manually, in the collection interface itself (that is, not through the site\code)?

Hi Tal,

The hook will work when adding or editing DB entries manually.
Therefore, you should add the code to the beforeInsert function (otherwise, you won’t be able to add a new entry manually):

if (!item.uniqueField) {
    return item
}

in the beginning of the hook function.

Cool. Thanks!
If you have time, I’d love to understand the logic behind this last part. Why is it necessary?
I’m guessing that it’s because otherwise, when I open a new line in the DB, it will somehow identify the still-empty value in the field as an already existing value. Am I right?

Just for future users - you need to add “.ne(”_id", item._id)" to the query on the update function (you can also add it in the Insert function - won’t hurt), or else you won’t be able to update other fields, once the unique field is not empty.

Hi there!
I’m a bit confused with this and tried almost everything still got nothing here :frowning:

i want my username field to be unique on droptest database and i use the #usernameinput to fill it.
What is the correct coding for this? How can i create a unique data on my “droptest” DB’s “username” field with “usernameinput” input?

Hi Mert. Each input in the form should be attached to a field in the collection.
Once that is done, then you use the function that Mor pasted here earlier, and you need to change the [test] in the beginning of the function name to the name of your collection (droptest?), and uniqueField to the username field you’re referring to. The item parameter that comes into the function should have the username property on it which you can use in your query. Something like this:

export async function droptest_beforeInsert(item, context) {
	const {items} = await wixData.query('droptest').eq("username", item.username).find()
	
	return !items.length ? item : Promise.reject()
}

Still no result.
I’m about to give up -.-
Isn’t there anyone out here to show their working version?

Mert, what is the address of your site, and which page is this on?

www.z365air.com
droptest/Update
:pray:
Have a surprise for you :joy:

Hi Mert,

I copied your site to my account and wrote this hooks:

import wixData from 'wix-data';

export async function droptest_beforeInsert(item, context) {
 if (!item.username) {
 return item;
        }
 
 const {items} = await wixData
        .query(context.collectionName)
        .eq("username", item.username)
        .find()
 
 return !items.length ? item : Promise.reject()
}

export async function droptest_beforeUpdate(item, context) {
 const {items} = await wixData
        .query(context.collectionName)
        .eq("username", item.username)
        .ne("_id", item._id)
        .find()
 
 return !items.length ? item : Promise.reject()
}

I couldn’t update the username from the page you suggested, but I checked this code from the content manager side and it worked as expected.

Please copy it, check if it works and let me know.

If it doesn’t, please explain IN DETAILS how do I update the username from the site (I don’t have any of your db content when I copy your site to my account).

Thank you

Hi I used you code in before hook insert in my database,

However the dynamic page the database is connected to has a submit button which isn’t working after I write this code on entering duplicate data
Can we add a custom error when he/she enters the same data instead of disabling the button

Screenshot of my code has been attached for reference

I desperately need
help making a column unique, kindly reply please
My email ID ashishg8898@gmail.com

Please add a new post rather than bumping up an old thread from 2018. You can also add a link to refer back to this post if needed as well.

For starters your beforeInsert datahook should be in a backend file called data.js as clearly stated in the Wix Datahook section in the Wix API Reference.
https://www.wix.com/corvid/reference/wix-data.Hooks.html
https://www.wix.com/corvid/reference/wix-data.Hooks.html#beforeInsert

Also, is your dataset called ‘Donationpage’ as that is what should be in front of the beforeInsert and not your actual dynamic page name.

Examples
A hook before an insert

// In data.js

export function myCollection_beforeInsert(item, context) {
  let hookContext = context;  // see below

  // some change to the received item

  return item;
}

/*
 * hookContext:
 *
 * {
 *   "collectionName": "myCollection",
 *   "userId":         "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3",
 *   "userRole":       "siteOwner"
 * }
 */

Old thread being closed.