Search code examples
couchbase-litecouchbase-view

How to retrieve data by property in Couchbase Lite?


My documents have the property docType that separated them based on the purpose of each type, in the specific case template or audit. However, when I do the following:

document.getProperty("docType").equals("template");
document.getProperty("docType").equals("audit");

The results of them are always the same, it returns every time all documents stored without filtering them by the docType.

Below, you can check the query function.

public static Query getData(Database database, final String type) {
    View view = database.getView("data");
    if (view.getMap() == null) {
        view.setMap(new Mapper() {
            @Override
            public void map(Map<String, Object> document, Emitter emitter) {
                if(String.valueOf(document.get("docType")).equals(type)){
                    emitter.emit(document.get("_id"), null);
                }
            }
        }, "4");
    }
    return view.createQuery();
}

Any hint?


Solution

  • This is not a valid way to do it. Your view function must be pure (it cannot reference external state such as "type"). Once that is created you can then query it for what you want by setting start and end keys, or just a set of keys in general to filter on.