Ordered sets of models with array-like operations, bulk database operations, and comprehensive data manipulation methods.
Create collection instances using the constructor or static forge method.
/**
* Collection constructor
* @param {Model[]} [models] - Initial array of models
* @param {object} [options] - Configuration options
* @param {Function|string} [options.comparator] - Sorting comparator function or attribute name
*/
new Collection(models?: Model[], options?: object);
/**
* Create collection instance without 'new' keyword
* @param {Model[]} [models] - Initial array of models
* @param {object} [options] - Configuration options
* @returns {Collection} New collection instance
*/
Collection.forge(models?: Model[], options?: object): Collection;Usage Examples:
// Empty collection
const users = new Users();
// Collection with initial models
const users = Users.forge([user1, user2, user3]);
// Collection with comparator
const sortedUsers = Users.forge([], {
comparator: 'name' // Sort by name attribute
});
const customSort = Users.forge([], {
comparator: (a, b) => a.get('created_at') - b.get('created_at')
});Core properties for collection configuration and state.
interface CollectionProperties {
/** Model constructor for collection items */
model: ModelConstructor;
/** Sorting comparator function or attribute name */
comparator: Function | string;
/** Array of models in collection */
models: Model[];
/** Number of models in collection */
length: number;
}Methods for fetching and querying collections from the database.
/**
* Fetch collection from database
* @param {object} [options] - Fetch options
* @param {string[]} [options.withRelated] - Relations to eager load
* @param {boolean} [options.require=false] - Throw if empty
* @param {object} [options.transacting] - Transaction object
* @returns {Promise<Collection>} Fetched collection
*/
fetch(options?: {
withRelated?: string[],
require?: boolean,
transacting?: Transaction,
debug?: boolean
}): Promise<Collection>;
/**
* Fetch single model from collection query
* @param {object} [options] - Fetch options
* @returns {Promise<Model>} Single model from query
*/
fetchOne(options?: object): Promise<Model>;
/**
* Load relations on all models in collection
* @param {string|string[]} relations - Relation names to load
* @param {object} [options] - Load options
* @returns {Promise<Collection>} Collection with loaded relations
*/
load(relations: string | string[], options?: object): Promise<Collection>;
/**
* Count records matching collection query
* @param {string} [column='*'] - Column to count
* @param {object} [options] - Count options
* @returns {Promise<number>} Record count
*/
count(column?: string, options?: object): Promise<number>;
/**
* Fetch paginated results
* @param {object} [options] - Pagination options
* @returns {Promise<{models: Collection, pagination: object}>} Paginated results
*/
fetchPage(options?: {
page?: number,
pageSize?: number,
limit?: number,
offset?: number,
withRelated?: string[],
transacting?: Transaction
}): Promise<{models: Collection, pagination: object}>;Usage Examples:
// Fetch all users
const users = await Users.forge().fetch();
// Fetch with relations
const usersWithPosts = await Users.forge().fetch({
withRelated: ['posts', 'profile']
});
// Fetch single user
const user = await Users.forge().where('email', 'alice@example.com').fetchOne();
// Paginated fetch
const {models, pagination} = await Users.forge().fetchPage({
page: 1,
pageSize: 10,
withRelated: ['posts']
});Methods for adding, removing, and managing models within collections.
/**
* Add models to collection
* @param {Model|Model[]} models - Models to add
* @param {object} [options] - Add options
* @param {number} [options.at] - Index to insert at
* @param {boolean} [options.merge=false] - Merge with existing models
* @returns {Collection} Collection instance for chaining
*/
add(models: Model | Model[], options?: {
at?: number,
merge?: boolean,
silent?: boolean
}): Collection;
/**
* Remove models from collection
* @param {Model|Model[]} models - Models to remove
* @param {object} [options] - Remove options
* @returns {Collection} Collection instance for chaining
*/
remove(models: Model | Model[], options?: {
silent?: boolean
}): Collection;
/**
* Replace all models in collection
* @param {Model[]} [models] - New models for collection
* @param {object} [options] - Reset options
* @returns {Collection} Collection instance for chaining
*/
reset(models?: Model[], options?: {
silent?: boolean
}): Collection;
/**
* Add model to end of collection
* @param {Model} model - Model to add
* @param {object} [options] - Push options
* @returns {Collection} Collection instance for chaining
*/
push(model: Model, options?: object): Collection;
/**
* Remove and return last model
* @param {object} [options] - Pop options
* @returns {Model} Removed model
*/
pop(options?: object): Model;
/**
* Add model to beginning of collection
* @param {Model} model - Model to add
* @param {object} [options] - Unshift options
* @returns {Collection} Collection instance for chaining
*/
unshift(model: Model, options?: object): Collection;
/**
* Remove and return first model
* @param {object} [options] - Shift options
* @returns {Model} Removed model
*/
shift(options?: object): Model;
/**
* Create new model and add to collection
* @param {object} attributes - Model attributes
* @param {object} [options] - Create options
* @returns {Promise<Model>} Created model
*/
create(attributes: object, options?: {
wait?: boolean,
transacting?: Transaction
}): Promise<Model>;
/**
* Update collection with new set of models
* @param {Model[]} models - New model set
* @param {object} [options] - Set options
* @returns {Collection} Collection instance for chaining
*/
set(models: Model[], options?: {
add?: boolean,
remove?: boolean,
merge?: boolean
}): Collection;Methods for accessing and searching models within collections.
/**
* Get model at specific index
* @param {number} index - Index position
* @returns {Model} Model at index
*/
at(index: number): Model;
/**
* Get model by ID
* @param {*} id - Model ID to find
* @returns {Model} Model with matching ID
*/
get(id: any): Model;
/**
* Get model by client ID
* @param {string} cid - Client ID to find
* @returns {Model} Model with matching client ID
*/
getByCid(cid: string): Model;
/**
* Find models matching attributes
* @param {object} attributes - Attributes to match
* @returns {Model[]} Array of matching models
*/
where(attributes: object): Model[];
/**
* Create shallow copy of collection
* @returns {Collection} Cloned collection
*/
clone(): Collection;
/**
* Get first model in collection
* @returns {Model} First model
*/
first(): Model;
/**
* Get last model in collection
* @returns {Model} Last model
*/
last(): Model;
/**
* Extract portion of collection
* @param {number} [start] - Start index
* @param {number} [end] - End index
* @returns {Model[]} Array slice of models
*/
slice(start?: number, end?: number): Model[];Methods for converting collections to JSON and data export.
/**
* Convert collection to JSON array
* @param {object} [options] - Serialization options
* @returns {object[]} Array of model JSON representations
*/
toJSON(options?: {
shallow?: boolean,
omitPivot?: boolean
}): object[];
/**
* Serialize collection and model relations
* @param {object} [options] - Serialization options
* @returns {object[]} Serialized collection data
*/
serialize(options?: object): object[];Methods for building database queries on collections.
/**
* Access or modify underlying query builder
* @param {Function} [callback] - Function to modify query builder
* @returns {Collection} Collection instance for chaining
*/
query(callback?: (queryBuilder: Knex.QueryBuilder) => void): Collection;
/**
* Add where clause to collection query
* @param {...*} args - Where clause arguments
* @returns {Collection} Collection instance for chaining
*/
where(...args: any[]): Collection;
/**
* Add order by clause
* @param {string} column - Column to order by
* @param {string} [direction='asc'] - Sort direction
* @returns {Collection} Collection instance for chaining
*/
orderBy(column: string, direction?: 'asc' | 'desc'): Collection;Collections proxy many Lodash array methods for data manipulation.
/**
* Iterate over models in collection
* @param {Function} iteratee - Function called for each model
* @param {*} [context] - Context for iteratee function
* @returns {Collection} Collection instance for chaining
*/
forEach(iteratee: (model: Model, index: number) => void, context?: any): Collection;
/**
* Transform models using iteratee function
* @param {Function} iteratee - Transformation function
* @param {*} [context] - Context for iteratee
* @returns {Array} Array of transformed values
*/
map(iteratee: (model: Model, index: number) => any, context?: any): any[];
/**
* Reduce collection to single value
* @param {Function} iteratee - Reducer function
* @param {*} [accumulator] - Initial accumulator value
* @param {*} [context] - Context for iteratee
* @returns {*} Reduced value
*/
reduce(iteratee: (accumulator: any, model: Model, index: number) => any, accumulator?: any, context?: any): any;
/**
* Find first model matching predicate
* @param {Function|object} predicate - Test function or attributes object
* @param {*} [context] - Context for predicate
* @returns {Model} First matching model
*/
find(predicate: Function | object, context?: any): Model;
/**
* Filter models matching predicate
* @param {Function|object} predicate - Test function or attributes object
* @param {*} [context] - Context for predicate
* @returns {Model[]} Array of matching models
*/
filter(predicate: Function | object, context?: any): Model[];
/**
* Reject models matching predicate
* @param {Function|object} predicate - Test function or attributes object
* @param {*} [context] - Context for predicate
* @returns {Model[]} Array of non-matching models
*/
reject(predicate: Function | object, context?: any): Model[];
/**
* Test if all models match predicate
* @param {Function|object} predicate - Test function or attributes object
* @param {*} [context] - Context for predicate
* @returns {boolean} True if all models match
*/
every(predicate: Function | object, context?: any): boolean;
/**
* Test if any model matches predicate
* @param {Function|object} predicate - Test function or attributes object
* @param {*} [context] - Context for predicate
* @returns {boolean} True if any model matches
*/
some(predicate: Function | object, context?: any): boolean;
/**
* Check if collection includes value
* @param {*} value - Value to check for
* @param {number} [fromIndex] - Index to start search
* @returns {boolean} True if value found
*/
includes(value: any, fromIndex?: number): boolean;
/**
* Invoke method on all models
* @param {string} methodName - Method name to invoke
* @param {...*} args - Arguments to pass to method
* @returns {Array} Array of method return values
*/
invoke(methodName: string, ...args: any[]): any[];
/**
* Extract attribute values from all models
* @param {string} attribute - Attribute name to extract
* @returns {Array} Array of attribute values
*/
pluck(attribute: string): any[];
/**
* Check if collection is empty
* @returns {boolean} True if collection has no models
*/
isEmpty(): boolean;
/**
* Get first n models
* @param {number} [n=1] - Number of models to take
* @returns {Model[]} Array of first n models
*/
head(n?: number): Model[];
/**
* Get all but first n models
* @param {number} [n=1] - Number of models to skip
* @returns {Model[]} Array excluding first n models
*/
tail(n?: number): Model[];
/**
* Create collection without specified models/values
* @param {...*} values - Values to exclude
* @returns {Model[]} Array without specified values
*/
without(...values: any[]): Model[];
/**
* Get models not in other collection
* @param {Collection|Model[]} other - Other collection to compare
* @returns {Model[]} Models not in other collection
*/
difference(other: Collection | Model[]): Model[];Special methods for working with Promise-returning functions on collections.
/**
* Invoke async method on all models and wait for results
* @param {string} methodName - Method name to invoke
* @param {...*} args - Arguments to pass to method
* @returns {Promise<Array>} Promise resolving to array of results
*/
invokeThen(methodName: string, ...args: any[]): Promise<any[]>;
/**
* Map models using Promise-returning function
* @param {Function} iteratee - Function returning Promise
* @param {*} [context] - Context for iteratee
* @returns {Promise<Array>} Promise resolving to array of results
*/
mapThen(iteratee: (model: Model, index: number) => Promise<any>, context?: any): Promise<any[]>;
/**
* Reduce models using Promise-returning function
* @param {Function} iteratee - Reducer function returning Promise
* @param {*} [initialValue] - Initial accumulator value
* @param {*} [context] - Context for iteratee
* @returns {Promise<*>} Promise resolving to final accumulator value
*/
reduceThen(iteratee: (accumulator: any, model: Model, index: number) => Promise<any>, initialValue?: any, context?: any): Promise<any>;Special methods available only on collections from belongsToMany relations.
/**
* Attach models to many-to-many relation
* @param {*|Array} ids - Model IDs to attach
* @param {object} [options] - Attach options
* @returns {Promise<Collection>} Collection after attach
*/
attach(ids: any | any[], options?: {
transacting?: Transaction
}): Promise<Collection>;
/**
* Detach models from many-to-many relation
* @param {*|Array} [ids] - Model IDs to detach (all if not specified)
* @param {object} [options] - Detach options
* @returns {Promise<Collection>} Collection after detach
*/
detach(ids?: any | any[], options?: {
transacting?: Transaction
}): Promise<Collection>;
/**
* Update pivot table attributes
* @param {object} attributes - Attributes to update on pivot
* @param {object} [options] - Update options
* @returns {Promise<Collection>} Updated collection
*/
updatePivot(attributes: object, options?: {
query?: Function,
transacting?: Transaction
}): Promise<Collection>;
/**
* Include additional pivot columns in results
* @param {...string} columns - Pivot column names to include
* @returns {Collection} Collection with pivot columns
*/
withPivot(...columns: string[]): Collection;const Users = bookshelf.collection('Users', {
model: User,
// Custom comparator for sorting
comparator: 'created_at',
// Custom instance methods
active() {
return this.filter(user => user.get('active'));
},
byRole(role) {
return this.filter(user => user.get('role') === role);
},
// Initialize method
initialize() {
this.on('add', this.onModelAdded);
},
onModelAdded(model) {
console.log('Added user:', model.get('name'));
}
}, {
// Static methods
findActive() {
return this.forge().query(qb => {
qb.where('active', true);
}).fetch();
}
});