apache / couchdb-nano

Nano: The official Apache CouchDB library for Node.js
https://www.npmjs.com/package/nano
Apache License 2.0
651 stars 165 forks source link

Pass arguments in couchdb-nano view function #217

Closed soubhikchatterjee closed 4 years ago

soubhikchatterjee commented 4 years ago

I am using nodejs's nano npm module and couchdb to get the total number of documents based on a status message that I should be able to pass in a couchdb view.

The view looks like the following.

{
    _id: "_design/docCount",
    views: {
      fileCountByStatus: {
        reduce: "_count",
        map:
          'function (doc) {\n  if(doc.status === "COMPLETE") {\n    emit(doc._id, 1);\n  }\n}'
      },
    },
    language: "javascript"
  }

I am accessing the above view using nano's view function.

My question is, is there anyway I can pass the doc status using the view function instead of hardcoding it (COMPLETE in the above case)

glynnbird commented 4 years ago

A great question, not necessarily anything to do with the Nano library, but a great CouchDB question all the same.

The general case is to create an index on status with a map function like this:

function(doc) {
  emit(doc.status, 1)
}

Then you can query the view for any value of status

db.view('mydesigndoc', 'myview', { key: 'complete' })
// or
db.view('mydesigndoc', 'myview', { key: 'new' })
soubhikchatterjee commented 4 years ago

@glynnbird

Hmm, i dont think this is a very scalable approach from couchdb. What if there are multiple conditions along with status? What if tomorrow a new requirement for adding a new condition arises? Do we have to create indexes everytime?

What I am trying to achieve here is building a pagination for my frontend, and for the same i need to get a count of the total number of records based on one or more conditions.

Can this be achieved without using views? If no, is there no other option?

Thanks

soubhikchatterjee commented 3 years ago

@glynnbird Support I have to filter by two queries instead of one, how do I do it in your example?