couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Traun Leyden <>
Subject Sort a query by a time-senstive criteria
Date Mon, 11 Mar 2013 23:49:09 GMT
I want to be able to sort a list of users by how much they've spent in the
last 6 months.

The document has a structure of:

  "purchases": [ {"type":"purchase","time":"2012-11-05
17:37:52","spent":50}, ...]

Here's how I'm planning on writing the index:

var cutoffDate = new Date();
cutoffDate.setMonth(cutoffDate.getMonth() - 6);
var total6m = 0;
doc.purchases.forEach(function(purchase) {
  if((new Date(purchase.time)) > cutoffDate)) {
    spent6m += purchase.spent;
index('spent6m', spent6m, {'store':'yes'});

The disadvantage to this approach is that the indexed data quickly gets
stale, because "new Date()" is only evaluated at index time and not when
the query is run.   Essentially it breaks the CouchDB rule of not having
the view depend on external data.

As a workaround, I'm thinking of adding a new field to the user object to
store the purchase amount for the last 6 months, as well as adding a
nightly process to update that field to keep the value from getting stale
as time progresses.

Is this the recommended approach or is there a cleaner way?


  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message