Skip to content

quickmodel / QModelCollection

Class: QModelCollection<TInstance> ​

Typed, immutable wrapper around an array of QModel instances.

Provides fluent filtering, sorting, pagination, grouping, serialization, and rule-checking over a homogeneous collection of QModel instances.

Create via the static from() factory or the Model.collection() static alias.

Example ​

typescript
const users = QModelCollection.from(UserModel, rawRows);

users
  .$qWhere(u => u.active)
  .$qSortBy('name')
  .$qPaginate(1, 10)
  .$qToArray(); // → UserModel[]

users.$qGroupBy('role');  // → Record<string, UserModel[]>
users.$qSerialize();      // → plain object array

See ​

Type Parameters ​

TInstance ​

TInstance extends IQCollectionItem

The QModel class instance type.

Accessors ​

$qIsEmpty ​

Get Signature ​

get $qIsEmpty(): boolean

Returns true when the collection contains no elements.

Example ​
typescript
QModelCollection.from(UserModel, []).$qIsEmpty; // → true
Returns ​

boolean


$qSize ​

Get Signature ​

get $qSize(): number

Number of instances in the collection.

Returns ​

number

Methods ​

$qAvg() ​

$qAvg(field): number

Returns the arithmetic average of a numeric field across all instances. Returns 0 for an empty collection.

Parameters ​

field ​

keyof TInstance

Name of a numeric property on the model.

Returns ​

number

Example ​

typescript
col.$qAvg('price'); // → 2.3
col.$qAvg('score'); // → 87.5

$qCheckAllRules() ​

$qCheckAllRules(): IQCollectionRulesResult

Runs $qCheckRules() on every instance in the collection.

Returns ​

IQCollectionRulesResult

{ valid, errors } where errors includes the index, field, and message for each rule failure across all instances.


$qCount() ​

$qCount(predicate?): number

Counts the number of instances that satisfy predicate. When called without arguments, returns the total collection size.

Parameters ​

predicate? ​

(item) => boolean

Optional filter function.

Returns ​

number

Example ​

typescript
col.$qCount();                       // → 5
col.$qCount(u => u.active === true); // → 3

$qEvery() ​

$qEvery(predicate): boolean

Returns true when every instance satisfies predicate. Returns true for an empty collection (vacuous truth).

Parameters ​

predicate ​

(item) => boolean

A function receiving a model instance and returning a boolean.

Returns ​

boolean

Example ​

typescript
col.$qEvery(u => u.age >= 18); // → true

$qFind() ​

$qFind(predicate): TInstance | undefined

Returns the first instance satisfying predicate, or undefined.

Parameters ​

predicate ​

(item) => boolean

A function receiving a model instance and returning true to match.

Returns ​

TInstance | undefined


$qFirst() ​

$qFirst(): TInstance | undefined

Returns the first instance in the collection, or undefined when empty.

Returns ​

TInstance | undefined

Example ​

typescript
col.$qFirst()?.name; // → 'Alice'

$qFlatMap() ​

$qFlatMap<TResult>(transform): TResult[]

Applies transform to each instance and flattens the result one level.

Type Parameters ​

TResult ​

TResult

Parameters ​

transform ​

(item) => TResult[]

A function receiving a model instance and returning an array.

Returns ​

TResult[]

Example ​

typescript
col.$qFlatMap(u => [u.name, u.email]); // → ['Alice', 'a@b.com', 'Bob', ...]

$qGroupBy() ​

$qGroupBy(field): Record<string, TInstance[]>

Groups the collection by the string value of field.

Parameters ​

field ​

keyof TInstance

Name of the property to group by.

Returns ​

Record<string, TInstance[]>

A Record mapping group keys to arrays of model instances.

Example ​

typescript
const byRole = col.$qGroupBy('role');
byRole['admin']; // → UserModel[]

$qLast() ​

$qLast(): TInstance | undefined

Returns the last instance in the collection, or undefined when empty.

Returns ​

TInstance | undefined

Example ​

typescript
col.$qLast()?.name; // → 'Eve'

$qMap() ​

$qMap<TResult>(transform): TResult[]

Applies transform to each instance and returns a plain array of the results.

Unlike toArray(), this returns transformed values rather than model instances.

Type Parameters ​

TResult ​

TResult

Parameters ​

transform ​

(item) => TResult

A function receiving a model instance and returning any value.

Returns ​

TResult[]

Example ​

typescript
col.$qMap(u => u.name);        // → ['Alice', 'Bob', ...]
col.$qMap(u => u.$qSerialize()); // → plain-object array

$qMax() ​

$qMax(field): TInstance | undefined

Returns the instance with the maximum value of field, or undefined when empty.

Parameters ​

field ​

keyof TInstance

Name of a numeric property (or string-comparable property) on the model.

Returns ​

TInstance | undefined

Example ​

typescript
col.$qMax('price')?.name; // → 'Elderberry'

$qMin() ​

$qMin(field): TInstance | undefined

Returns the instance with the minimum value of field, or undefined when empty.

Parameters ​

field ​

keyof TInstance

Name of a numeric property (or string-comparable property) on the model.

Returns ​

TInstance | undefined

Example ​

typescript
col.$qMin('price')?.name; // → 'Banana'

$qPaginate() ​

$qPaginate(page, pageSize): QModelCollection<TInstance>

Returns a new collection representing a single page of results.

Pages start at 1. If the requested page is beyond the available data, an empty collection is returned.

Parameters ​

page ​

number

1-based page number.

pageSize ​

number

Number of items per page.

Returns ​

QModelCollection<TInstance>

Example ​

typescript
const page1 = col.$qPaginate(1, 10); // items 0–9
const page2 = col.$qPaginate(2, 10); // items 10–19

$qReduce() ​

$qReduce<TAcc>(reducer, initial): TAcc

Reduces the collection to a single accumulated value.

Type Parameters ​

TAcc ​

TAcc

Parameters ​

reducer ​

(acc, item) => TAcc

A function receiving the current accumulator and the current instance.

initial ​

TAcc

The initial accumulator value.

Returns ​

TAcc

Example ​

typescript
col.$qReduce((total, p) => total + p.price, 0); // → sum of prices

$qSerialize() ​

$qSerialize(options?): ReturnType<TInstance["$qSerialize"]>[]

Serializes every instance in the collection using the model's serialize() method.

Parameters ​

options? ​

IQSerializationOptions

Optional serialization options forwarded to each instance.

Returns ​

ReturnType<TInstance["$qSerialize"]>[]

An array of plain serialized objects.

Example ​

typescript
col.serialize({ pick: ['id', 'name'] }); // → [{ id, name }, ...]

$qSome() ​

$qSome(predicate): boolean

Returns true when at least one instance satisfies predicate. Returns false for an empty collection.

Parameters ​

predicate ​

(item) => boolean

A function receiving a model instance and returning a boolean.

Returns ​

boolean

Example ​

typescript
col.$qSome(u => u.role === 'admin'); // → true

$qSortBy() ​

$qSortBy(field, options?): QModelCollection<TInstance>

Returns a new collection sorted by field.

Numbers and strings are supported. Other types fall back to string comparison. Does not mutate the original collection.

Parameters ​

field ​

keyof TInstance

Name of the property to sort by.

options? ​

ISortByOptions

{ order: 'desc' } for descending order (default: 'asc').

Returns ​

QModelCollection<TInstance>

Example ​

typescript
const sorted = col.$qSortBy('age', { order: 'desc' });

$qSum() ​

$qSum(field): number

Returns the sum of a numeric field across all instances. Returns 0 for an empty collection.

Parameters ​

field ​

keyof TInstance

Name of a numeric property on the model.

Returns ​

number

Example ​

typescript
col.$qSum('price'); // → 7.0
col.$qSum('stock'); // → 390

$qToArray() ​

$qToArray(): TInstance[]

Returns a plain array of model instances.

The returned array is a shallow copy — mutation does not affect the collection.

Returns ​

TInstance[]


$qToCSV() ​

$qToCSV(options?): string

Exports the collection to a CSV-formatted string (RFC 4180).

Values are serialized via each instance's serialize() method. Cells that contain the delimiter, a newline, or a double-quote are automatically wrapped in double-quotes; embedded double-quotes are escaped by doubling.

Parameters ​

options? ​

IQCSVOptions

Optional CSV generation options.

Returns ​

string

A CSV string. Returns '' when the collection is empty.

Examples ​

Basic export

typescript
const csv = UserCollection.from(UserModel, rows).$qToCSV();
// id,name,email
// 1,Alice,alice@example.com
// 2,Bob,bob@example.com

Semicolon-delimited, subset of fields

typescript
col.$qToCSV({ delimiter: ';', fields: ['name', 'email'] });

See ​

IQCSVOptions


$qToJSON() ​

$qToJSON(): string

Returns a JSON string representing the serialized array.

Returns ​

string

Example ​

typescript
const json = col.$qToJSON();
// '[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]'

$qToMap() ​

$qToMap(field): Map<unknown, TInstance>

Returns a Map indexing each instance by the string or number value of field. When duplicate values exist, the last occurrence wins.

Parameters ​

field ​

keyof TInstance

Name of the property to use as the map key.

Returns ​

Map<unknown, TInstance>

Example ​

typescript
const byId = col.$qToMap('id');
byId.get(1)?.name; // → 'Alice'

$qUnique() ​

$qUnique(field): QModelCollection<TInstance>

Returns a new collection keeping only the first occurrence of each unique value of field. Subsequent items sharing the same field value are discarded.

Parameters ​

field ​

keyof TInstance

Name of the property whose value determines uniqueness.

Returns ​

QModelCollection<TInstance>

Example ​

typescript
col.$qUnique('category'); // one item per category

$qWhere() ​

$qWhere(predicate): QModelCollection<TInstance>

Returns a new collection containing only the instances that satisfy predicate.

Does not mutate the original collection.

Parameters ​

predicate ​

(item) => boolean

A function receiving a model instance and returning true to keep it.

Returns ​

QModelCollection<TInstance>

Example ​

typescript
const admins = col.$qWhere(u => u.role === 'admin');

from() ​

static from<TInstance>(ctor, data): QModelCollection<TInstance>

Creates a QModelCollection from a raw data array.

Each element is instantiated via new Model(row).

Type Parameters ​

TInstance ​

TInstance extends IQCollectionItem

Parameters ​

ctor ​

IQModelCtor<TInstance>

The QModel subclass constructor.

data ​

readonly object[]

Array of raw plain-object rows.

Returns ​

QModelCollection<TInstance>

Example ​

typescript
const col = QModelCollection.from(UserModel, await db.select().from(users));

fromArray() ​

static fromArray<TInstance>(ctor, data): QModelCollection<TInstance>

Creates a QModelCollection from a raw data array. Alias for QModelCollection.from.

Type Parameters ​

TInstance ​

TInstance extends IQCollectionItem

Parameters ​

ctor ​

IQModelCtor<TInstance>

The QModel subclass constructor.

data ​

readonly object[]

Array of raw plain-object rows.

Returns ​

QModelCollection<TInstance>

Example ​

typescript
const col = QModelCollection.fromArray(UserModel, rows);

fromJSON() ​

static fromJSON<TInstance>(ctor, json): QModelCollection<TInstance>

Creates a QModelCollection from a JSON string.

Parses json with JSON.parse and delegates to from(). Each element is instantiated via new ctor(row) so all transformers run.

Type Parameters ​

TInstance ​

TInstance extends IQCollectionItem

Parameters ​

ctor ​

IQModelCtor<TInstance>

The QModel subclass constructor.

json ​

string

A JSON string produced by $qToJSON() or JSON.stringify(col).

Returns ​

QModelCollection<TInstance>

A new QModelCollection<TInstance>.

Throws ​

If json is not valid JSON.

Throws ​

If the parsed value is not an array.

Example ​

typescript
const json = col.$qToJSON();
const restored = QModelCollection.fromJSON(UserModel, json);
restored.$qFirst(); // → UserModel instance

toJSON() ​

toJSON(): ReturnType<TInstance["$qSerialize"]>[]

Implements the JS toJSON protocol — returns a plain array of serialized items so that JSON.stringify(collection) and JSON.stringify({ col }) work correctly.

Returns ​

ReturnType<TInstance["$qSerialize"]>[]

See ​

QModelCollection.$qToJSON — returns a JSON string (convenience shortcut)