1

I have a view which filters out the data for me. I want to add a check in my search criteria => If a field does not exist in document don't consider that document.

Here is my view code, studentId may not be present in all the documents.

function (doc, meta) {
   if(meta.id && meta.id.indexOf("DOCUMENT_") == 0 && doc.studentId != null) {
   emit([doc.studentId, doc.studentStatus, doc.studentName], null);
  }
}

Any pointers?

User0911
  • 1,552
  • 5
  • 22
  • 33
  • What is your question, could you be more precise? – Julian Go Oct 21 '15 at 21:59
  • @JulianGo - Here it is => I want to add a check in my search criteria => If a field does not exist in document don't consider that document. – User0911 Oct 22 '15 at 02:57
  • then your code should be doing the trick... see FuzzyAmi's answer for improvements. maybe you also want you studentId test to just be `if (doc.studentId && meta.id.indexOf("DOCUMENT_") == 0)`? – Simon Baslé Oct 22 '15 at 08:10

2 Answers2

2

In your code, simply use the same syntax you used earlier in the if statement:

if(doc.studentId && meta.id && meta.id.indexOf("DOCUMENT_") == 0) ...

Note that the following

if(doc.studentId...

will return true if studentId is defined, otherwise false.

theMayer
  • 15,456
  • 7
  • 58
  • 90
0

just a tiny optimization - you probably want to move to doc.studentId to the beginning of the condition if many of the docs in the bucket are missing it.

also, dont all docs have meta.id? seems weird to test for it...

FuzzyAmi
  • 7,543
  • 6
  • 45
  • 79
  • one more thing: views are great, but dont rely on them to bring you the most updated data: they may even return data that has already been deleted. If the docs you're accessing are not huge AND you want the most updated data (especially if your docs are often deleted), you should probably attach the doc to the view rather than emit the fields you want. This will increase the accuracy of the results (ensure deleted items are not retrieved, etc) – FuzzyAmi Oct 21 '15 at 18:51
  • @fuzzyami: or query the view using Stale = false – Simon Baslé Oct 22 '15 at 08:07