I wanted to have a View that emits values based on keys that come from multiple documents and I managed to do it by getting linked documents inside the emit function but then my index is updated only when the base document is updated and not when one of the linked documents is being updated.
So my base documents are structured like these (minimal version):
Your idea is not possible given the way that views work. There is a requirement that the map function is “pure” (i.e. does not rely on any external state, and that any given set of input properties will always produce the same result). Anything you’d like to emit needs to be directly included in the document that is being indexed so the properties in question need to be a part of the visit document itself and not in a separate one.
The usual way to do this is to have both types of documents emit the same key (in this case the visitID), and the desired properties as the value. Then you can either query for all rows with the desired visitID and merge the values together, or you can use a reduce function that does the same thing.
(Also, it seems weird in your code that you’re putting all those values into the key. Did you intend to create a multi-level sort on (id, status, isComplete, patientID) or was that a mistake?)
Unfortunately we have some reasons to not change our data structure (it is already used in prod, it’s focused on offline first and try to avoid conflicts by keeping the atomicity of the data, etc.). I managed to fix it by combining 2 queries. I may update my answer once we get into couchbase lite 2.x (it seems the N1QL-like feature gives more flexibility on the way to get data out from local databases).