Couchbase adding same channel multiple times on update

I’m developing an android application using Couchbase Lite in the mobile end, Sync Gateway for the replication and Couchbase Community as the centralized database.

Everything works fine except the documents update. When any document is updated, the channel property is being overwritten, causing the document to lose the channels, and if I use a Sync function to add the channel channel(doc.channel) I end up with the same channel N times, where N is the times I have updated the document.

This is a problem because once the system hits production the users usually modify a document around 50-200 times and it would be a waste of data to have the same channel 50-200 times in the same document.

Is there a way to prevent this?

When any document is updated, the channel property is being overwritten, causing the document to lose the channels,

It sounds like you’re updating a document by replacing its properties with a new Map, overwriting the old properties. To preserve all properties, you should get the current properties, mutate that Map to change properties, then save the document with that modified Map.

if I use a Sync function to add the channel channel(doc.channel) I end up with the same channel N times

I don’t understand what you mean here; a doc can only be in a channel or not in a channel, it can’t appear more than once.

Then I must be doing something wrong. I have tried both of these to get the document’s properties:

Map<String, Object> newProperties = updatedDocument.getProperties();

Map<String, Object> newProperties = new HashMap<>(updatedDocument.getProperties());

and the first one gives me an error for trying to modify an inmutable object when I put the new property and the second one erases the channels.

As for this statement

I don’t understand what you mean here; a doc can only be in a channel or not in a channel, it can’t appear more than once.

I mean that if I use a Sync function to add the channel I end up with an array of channels like this after several updates:

"channels" : [
  "user_channel",
  "user_channel",
  "user_channel",
  "user_channel",
  "user_channel",
  "user_channel",
  "user_channel"
]

That’s not the sync function adding it, it’s your code somewhere. Sync Gateway Sync Functions do not modify documents, they simply route them based on their state. You should examine or show how you update the document.

There’s something wrong with how you’re updating your document, then. You’re in charge of that channels property – there’s nothing magic about it at all. Somehow you’re adding items to the array in your code.