Sorting Results
Sort your data in ascending or descending order using orderBy and orderByDescending.
Quick Navigation
Ascending Sort
Sort data in ascending order:
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).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:
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).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 multiple sort operations for complex sorting:
// Sort by category first, then by price
const productsByCategoryAndPrice = await dataStore.products
.sort((p) => p.category)
.sort((p) => p.price)
.toArrayAsync();
Combined with Filtering
Sort filtered results:
const expensiveProductsSorted = await dataStore.products
.where((p) => p.price > 100)
.orderByDescending((p) => p.price)
.toArrayAsync();