Get query by id not working

I’m trying this function but isn’t working. It’s like one in the ToDoLite example. I want to pick one document with the given id but isn’t working this way:

private Query getQueryById(String userId) {
View view = CouchbaseHelper.getDatabase().getView(VIEW_NAME);
if (view.getMap() == null) {
Mapper map = (document, emitter) -> {
if (DOC_TYPE.equals(document.get("type"))) {
emitter.emit(document.get("_id"), document);
view.setMap(map, "1");
Query query = view.createQuery();
List<Object> keys = new ArrayList<>();
return query;
and it returns null, but if I comment

// List<Object> keys = new ArrayList<>();
// keys.add(userId);
// query.setKeys(keys);

it returns the right document. Is this a bug or I’m doing something wrong? Which should be the right way to do this?

There are a few issues here.

First, if the user ID is the same as the document ID, you can just retrieve the document directly. No need for a View.

Second, you shouldn’t have the map function depend on an external variable. So what you have is ok, as long as DOC_TYPE is fixed, but I wanted to point it out to be sure.

Third, emitting the document ID as a key is a red flag. That rarely helps your ability to query. (It often does make sense to query based on the document ID if you use custom IDs. You’d most often just use an all-docs query. Creating a View could help performance. Otherwise there’s no point.)

Fourth, you almost never want to emit the entire document. That bloats the index created by the View. Just retrieve the document by ID. You get the document ID for free in your query results.

Your question is very similar to this ongoing thread. Take a look and see if it helps.