Selecting Fields

Use map to select specific fields or create computed values from your data.

Quick Navigation

Select Specific Fields

Project only the fields you need:

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();

// Select specific fields
const productSummaries = await dataStore.products
    .map(p => ({
        id: p._id,
        name: p.name,
        price: p.price
    }))
    .toArrayAsync();

Computed Fields

Create computed values and transformations:

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();

// Computed fields
const productWithComputed = await dataStore.products
    .map(p => ({
        name: p.name,
        price: p.price,
        isExpensive: p.price > 100,
        displayName: `${p.name} (${p.category})`
    }))
    .toArrayAsync();

Single Field Selection

Select just one field:

// Get only product names
const productNames = await dataStore.products.map((p) => p.name).toArrayAsync();

// Get only prices
const productPrices = await dataStore.products
  .map((p) => p.price)
  .toArrayAsync();

Combined with Other Operations

Use field selection with filtering and sorting:

const expensiveProductNames = await dataStore.products
  .where((p) => p.price > 100)
  .sortDescending((p) => p.price)
  .map((p) => p.name)
  .toArrayAsync();