How to avoid duplication data issue in sync gateway?

Hi,
I created simple android application. I can add item and category. I am able to add same item/category using cURL command. item/category should be unique. I validated on android site. but when i create document with cURL i am able to create duplicate document. how to avoid this issue? how can i validate in sync function? And i need to validate maximum length also. can you help me?
this is my sync gateway config code
“adminInterface”: “0.0.0.0:4985”,
“interface”: “0.0.0.0:4984”,
“databases”: {
“test”: {
“server”: “—”,
“bucket”: “test”,
“users”: { “admin”:{“password”:“test1234”, “admin_channels”: ["*"]}},
“sync”: function(doc, oldDoc) { if (doc.type == "category") { channel(doc._id); access(doc.username,doc._id); } }
}
}
Thank you.

Uniqueness constraints are tricky. SQL databases implement them using indexes, but Sync Gateway doesn’t provide access to indexes in the sync function. Also, there can be race conditions if multiple clients insert duplicate documents at the same time.

In a document database, generally the best way to guarantee uniqueness is to put the unique properties into the document ID. In your case, put the item and category into the docID. Then duplicate docs will end up with the same docID, which means there’s only one document.

You then also need to add code to your sync function that validates that the actual docID matches the one based on the item/category properties.

1 Like

Thank you @jens . Now it is working fine.
I have offline issue. I have web application also. when mobile app is offline i added item(abc) and category(bca). i added item(abc) and category(bca) from web application also. when mobile app come to online, the mobile app documents(item - abc and category - bca) will be ‘conflict’/ delete right? is any way to solve this issue when app is offline?

Thank you.

No; there is no way to avoid conflicts in a system that supports offline activity. To prevent conflicts before they happen, the mobile app would have to write to the server every time it saved a document locally. Conflicts are the price you pay for the benefits of offline support.

1 Like

Thank you @jens
when i am creating item/category i am using doc_id as a item name/category name. so item / category can not be duplicate. but when i edit item/category document, there is a chance to duplicate item/ category. is any solution for this?
thank you