Taking current time in couchbase view

I am writing a couchbase view where I have to pick items created in last 1 hour along with some condition. I have a field created_at in each document which is creation time in milliseconds. I have written the following view:

function (doc, meta) {
  if(meta.id.indexOf('media')>-1 && doc.digest_notification == 1 && (new Date().getTime()-doc.created_at) < 3600000 )
    
    emit(doc.created_at, doc)
    
 
}

This view works correctly when just published. However, it stops working after some time. It continues to return documents even after 1 hour. It seems that value of new Date().getTime() is not working fine. Is this the correct way to write this view?

1 Like

Date().getTime() is not a deterministic function (meaning it returns a different value given the same parameters at each call). In this case It is evaluated at the time of indexing the item which can be arbitrary amount of time after the item is mutated depending on your view settings. However it is NOT reevaluated over time. To get this to work correctly, you should index all documents and query items created in the last hour during query time;

function (doc, meta) {
if(meta.id.indexOf(‘media’)>-1 && doc.digest_notification == 1 )
emit(doc.created_at, doc)
}

and query the view with startKey with the value of Date().getTime()-3600000.
thanks
-cihan

1 Like