String to date parsing in Couchbase map/reduce view

Published at 2018-12-28

Just a tiny tip if you ever find yourself in the tricky situation of trying to sort by a stringified date in Couchbase.

Say that you have a document that looks like this:

{
  "id": "superhero_1",
  "created": "2018-12-28T15:53:00+01:00",
  "name": "Clark Kent",
  "alias": "Superman",
  "strengths": [
    "laser eyes",
    "flying"
  ],
  "weaknesses": [
    "cryptonite"
  ]
}

The created field is saved with a ISO 8601 Notation. In couchbase it is hard to sort by. It's better to convert this to milliseconds using Javascript with views when querying the dataset. You can achieve this with the following query:

function (doc, meta) { 
  if (doc.created) { 
    emit(["created", Date.parse(doc.created)], { id: doc.id } );
  }
}

This will produce a key value pair that looks something like this:

{
  "key": ["created", 1546008780000],
  "value": { "id": "superhero_1" }
}

That's it! This format is easier to deal with in terms of sorting and I'm sure it has other applications as well. Hope you found this useful!

Avatar of Author

Karl SolgÄrd

Norwegian software developer. Eager to learn and to share knowledge. Sharing is caring! Follow on social: Twitter and LinkedIn. Email me: [email protected]