Editing the documents on syncing to the server


#1

I wished to capture the time stamp while the document is being synced to the server. In the code snippet below if the date_log attribute is null I am trying to capture the time stamp during the sync process.

“sync”: `
function(doc, oldDoc){
if(doc.type == “chat_message” && doc.date_log == null)
{
doc.date_log = Date.now();
}

			channel(doc.channels);
		}

But the above has no effect on the document. Kindly let me know if I have gone wrong somewhere.


#2

Hi,
You’re saying you want to update the date_log when it’s null but in your code it’s updating it when it is not null:

if(doc.type == "chat_message" && doc.date_log != null)

I guess you should have this instead

if(doc.type == "chat_message" && doc.date_log == null)

#3

Hi Idoguin,

That was a typo error. I have corrected the code now.

Thanking you,


#4

Actually I just realized that you were trying to change a doc in the sync function. I am afraid this is not possible. You cannot modify objects in the sync function.


#5

Hi Idoguin,

Thank you for the information. I was not aware about it.
Actually I am trying to create a chat application. Once an user messages another person I am creating 2 documents(1 for the sender and 1 for the receiver) with the relevant details. Now when I want to display the conversation I am sorting the documents by its time stamp pertaining to that user.

Now in this scenario, I have an issue pertaining to what if the user has changed the local time of the device. I have to use the local time since there might be a scenario the user might have no internet connection. The sorting will not be in a proper way. So I was trying to fetch the time at which the document got synced onto the server so that I could sort it according to it.

Please suggest a solution.

Thanking you,


#6

Hi - I have the same problem, did you figure out a solution?


#7

Hi, still not sure how to do this, maybe @jens has an idea.


#8

It’s generally better to use the client’s time, because there can be an arbitrarily long delay before the document gets synced to the server, if the client is offline or not running a continuous replication. This reflects the time the user actually created it, which is usually what people want to know (or sort by.)

Just make sure you store the time in UTC, of course. The usual format for JSON is ISO-8601. The iOS version of Couchbase Lite has a utility to convert times to this format; not sure about the other platforms.

You can’t add a timestamp (or anything else) in the sync function, because this is being called during replication, and replication doesn’t create new document revisions, it only transfers ones created on clients.