-1

I have a View in Couchbase that I use to retrieve my data. Simplified, my data bucket contains:

{
    "id" : 123,
    "key" : "some value"
},
{
    "id" : 456,
    "key" : ""
}
...

and I want to get all the docs where 'key' is present, but its value is empty.

If I use a view like this:

function (doc, meta) {
  if(doc.key)
    emit([doc.id], doc);
}

I get both the JSONs above, if I use a view like this:

function (doc, meta) {
  if(doc.key && doc.key == "")
    emit([doc.id], doc);
}

I get none of them. I want to get the json with id = 456. What is the correct syntax?

ocramot
  • 1,361
  • 28
  • 55

1 Answers1

0

That is because empty string is false in javascript

~ $ node 
> var x = ""
undefined
> x
''
> if (x && x == "") { console.log("it is empty") }
undefined
> if (x) { console.log("it is empty") }
undefined
> if (!x) { console.log("it is empty") }
it is empty
undefined

You should use something like

if(doc.key === "")

Triple equals will compare it to string more strictly

avsej
  • 3,822
  • 4
  • 26
  • 31
  • 1
    short and funny video about WAT effects in javascript and ruby :) https://www.destroyallsoftware.com/talks/wat – avsej Feb 19 '16 at 21:13
  • Thank you, it worked. (I still don't understand why do I have to use `if(doc.key === "")` instead of `if(doc.key && doc.key === "")`, though. What if there is a json without that `key`?). – ocramot Feb 22 '16 at 13:43
  • You can compare with `undefined`. Like `var doc = {x: ""}; doc.y == undefined` yields `true`, and `doc.x == undefined` gives you `false` – avsej Feb 23 '16 at 16:54