Ido Barash
Ido Barash

Reputation: 5122

Couchbase view documents older than one month

I am trying to create a couchbase view which retrieve the IDs of all the views that haven't been updated for more than one month. They also should not have the string ID in their key:

function (doc, meta) {

  if (meta.id.indexOf("ID") == -1) {
    var currentDate = new Date();
    var currentDateInMillis = currentDate.getTime();
    if (doc.lastTimestampMillis != null && doc.lastTimestampMillis < (currentDateInMillis - (30 * 24 * 60 * 60 * 1000))) {
      emit(meta.id, meta.id)
    }
  }
}

Notice that I have lastTimestampMillis field in my document.

Well, This code doesn't work.

Upvotes: 0

Views: 280

Answers (1)

David Ostrovsky
David Ostrovsky

Reputation: 2481

Instead of implementing the dates checking logic in the view code, just emit doc.lastTimestampMillis and then query for the dates you want. E.g. query.endkey(<now - 30d>) will give you all the timestamps up to 30 days ago. Since the emitted value only updates when the document changes, the view as you wrote it becomes stale almost immediately. Only emitting the timestamp has the advantage of letting you query any range of dates, as well as actually reflecting the correct timestamps at all times.

Upvotes: 3

Related Questions