Nativescript Couchbase: Ordered list


#1

Hi there, how can I get ordered documents stored in a couchbase database, for example: ordered by date asc or desc?

I am using nativescript-couchbase plugin.

Thanks and happy coding…


#4

Can you share your MapReduce View function?
because if I’m understanding correctly, the MapReduce should emit document sorted by the supplied filters


#5

Hi there, thanks for your help, this is how my code looks like:

this.database = new Couchbase(Globals.APP_ID.toLowerCase()+'notifications');
    this.database.createView("notifications", "1", function(document, emitter) {
    emitter.emit(document._id, document);
});

Then I return the notifications like this:

let notifications = [];
let rows = this.database.executeQuery("notifications");
for(let i = 0; i < rows.length; i++) {
    notifications.push(rows[i]);
}
return notifications;

I hope it helps, thanks!


#6

I’m not sure, but based on the issue pointed on Github here it seems you have to use JSON.stringify to order


#7

If you want to sort, instead of giving the document._id instead give the field you want to sort with. For example, lets say you want to sort based on notification title, then your emit function will be as follows:

this.database = new Couchbase(Globals.APP_ID.toLowerCase()+'notifications');
    this.database.createView("notifications", "1", function(document, emitter) {
    emitter.emit(document.title, document);
});

Also want to add, when you excuse query you can pass options as follows:

let rows = this.database.executeQuery("notifications", {descending : false, limit : 20,  skip : true, startKey: "your start key", endKey:"your end key"});

where these options are as follows:

  • startKey: the key to start at. The default value, null, means to start from the beginning.

  • endKey: the last key to return. The default value, null, means to continue to the end.

  • descending: If set to true, the keys will be returned in reverse order. (This also reverses the meanings of the startKey and endKey properties, since the query will now start at the highest keys and end at lower ones!)

  • limit: If nonzero, this is the maximum number of rows that will be returned.

  • skip: If nonzero, this many rows will be skipped (starting from the startKey if any.)

However, I’m still having trouble with multiple sorts, like for example using [lastname, firstname] in which we order with last name first and if same last name will be sorted by first name.

PS: instead of emiting the whole document in which case you are creating a duplicate index of your database, I find it better to build an object in the emit function where this object have the fields you want and have all the transformations already applied to it (e.g. regex, toLowerCase() … etc). so later you can easily search the rows of the executed query and retrieve documents from the database based on _id