Sorting Results
Sort your data in ascending or descending order using orderBy and orderByDescending.
Quick Navigation
Ascending Sort
Sort data in ascending order:
ts
import { DataStore } from "@routier/datastore";
import { s } from "@routier/core/schema";
import { MemoryPlugin } from "@routier/memory-plugin";
const productSchema = s.define("products", {
_id: s.string().key().identity(),
name: s.string(),
price: s.number(),
category: s.string(),
inStock: s.boolean(),
tags: s.string("computer", "accessory").array(),
createdDate: s.date().default(() => new Date())
}).compile();
class AppDataStore extends DataStore {
products = this.collection(productSchema).proxy().create();
constructor() {
super(new MemoryPlugin("app"));
}
}
const dataStore = new AppDataStore();
// Sort by price (ascending)
const productsByPrice = await dataStore.products
.sort(p => p.price)
.toArrayAsync();Descending Sort
Sort data in descending order:
ts
import { DataStore } from "@routier/datastore";
import { s } from "@routier/core/schema";
import { MemoryPlugin } from "@routier/memory-plugin";
const productSchema = s.define("products", {
_id: s.string().key().identity(),
name: s.string(),
price: s.number(),
category: s.string(),
inStock: s.boolean(),
tags: s.string("computer", "accessory").array(),
createdDate: s.date().default(() => new Date())
}).compile();
class AppDataStore extends DataStore {
products = this.collection(productSchema).proxy().create();
constructor() {
super(new MemoryPlugin("app"));
}
}
const dataStore = new AppDataStore();
// Sort by price (descending)
const productsByPriceDesc = await dataStore.products
.sortDescending(p => p.price)
.toArrayAsync();Multiple Sort Criteria
Chain sorts to order by more than one value. The first sort decides the order, and each later sort only orders rows that tie on every sort before it:
ts
// Sort by category first, then by price
const productsByCategoryAndPrice = await dataStore.products
.sort((p) => p.category)
.sort((p) => p.price)
.toArrayAsync();Every backend orders chained sorts the same way. A SQL backend runs them as one ORDER BY, with the columns in the order you wrote the sorts. Two dates with the same time are a tie, so the next sort decides between them.
Combined with Filtering
Sort filtered results:
ts
const expensiveProductsSorted = await dataStore.products
.where((p) => p.price > 100)
.orderByDescending((p) => p.price)
.toArrayAsync();