Q:

Couchbase & nodejs: View query with range, order and limited results

I am new to couchbase and I'm trying to understand how filtering, ordering and limiting results in a view work together.

Couchbase version: 3.0.1

I'm using nodejs as the SDK.
I have a map function like this
function (doc, meta) {
    if (doc.type !== 'item' || !doc.category) {
        return;
    }
    emit([doc.orderId, doc.category.id, doc.number], null);
}

And an item document that looks like this
{
    "id": 1,
    "type": "item",
    "number": 1203,
    "orderId": 2,
    "category": {
        "id": 10,
        "title": "Carpet"
    }
}

I would like to filter only items with orderId = 2 and category.id = 10, all this ordered by number descending. Because I have a paginator, I would like to display 20 items per page. I have thousands of items in the database.
With the query below, I have an error because of the order call. If I comment it, I find the results, filtered, limited and ordered by default by number ascending.
var order_id = 2,
    category_id = 10,
    limit = 20,
    skip = 0,

    range = [order_id, category_id],
    // suppose we have a valid couchbase connexion and a viewQuery object
    query = viewQuery.from('items', 'myView')
        .limit(limit)
        .skip(skip)
        .order(2) // 2 = DESC. This line doesn't work
        .include_docs(true)
        .range(range, range.concat([{}]), true);

bucket.query(query, function (err, docs) {
    console.log(err);
    console.log(docs);
});

The error says:

Error: query_parse_error: No rows can match your key range, reverse your start_key and end_key or set descending=false

Note that if I order ASC, the error occurs too. I have to remove the call to the .order() function to have my view behave properly.
Does anyone knows why?
Thanks

A:

When you order your query in descending order, you have to swap the order of the start and end keys as well (the parameters to the range method.)

