Fast document oriented javascript in-memory database
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Live, automatically updated views of collection data with persistent filtering and sorting. Dynamic views maintain their state and automatically update when the underlying collection changes.
Creates a new dynamic view attached to a collection with automatic updates.
/**
* Creates a new dynamic view
* @param collection - Source collection
* @param name - View name
* @param options - View configuration options
*/
constructor DynamicView(collection: Collection, name: string, options?: DynamicViewOptions);
interface DynamicViewOptions {
/** Persist filter pipeline */
persistent?: boolean;
/** Sort criteria array */
sortPriority?: string;
/** Minimum rebuild interval */
minRebuildInterval?: number;
}Usage Examples:
const users = db.getCollection('users');
// Create basic dynamic view
const activeUsers = users.addDynamicView('activeUsers');
// Create with options
const recentHires = users.addDynamicView('recentHires', {
persistent: true,
minRebuildInterval: 1000
});Apply persistent filters that automatically update when collection data changes.
/**
* Apply a find filter to the view
* @param query - MongoDB-style query object
* @param uid - Optional unique identifier for the filter
* @returns DynamicView for chaining
*/
applyFind(query: object, uid?: string): DynamicView;
/**
* Apply a where filter using custom function
* @param fun - Filter function returning boolean
* @param uid - Optional unique identifier for the filter
* @returns DynamicView for chaining
*/
applyWhere(fun: (obj: object) => boolean, uid?: string): DynamicView;
/**
* Remove all filters from the view
* @param options - Remove options
* @returns DynamicView for chaining
*/
removeFilters(options?: object): DynamicView;
/**
* Remove specific filter by unique identifier
* @param uid - Filter unique identifier
* @returns DynamicView for chaining
*/
removeFilter(uid: string): DynamicView;Usage Examples:
// Apply find filter
const activeUsers = users.addDynamicView('activeUsers')
.applyFind({ active: true });
// Apply multiple filters with IDs
const engineeringView = users.addDynamicView('engineering')
.applyFind({ department: 'Engineering' }, 'dept-filter')
.applyFind({ level: { $in: ['Senior', 'Lead'] } }, 'level-filter');
// Apply custom where filter
const recentLoginView = users.addDynamicView('recentLogin')
.applyWhere(obj => {
const lastLogin = new Date(obj.lastLogin);
const weekAgo = new Date();
weekAgo.setDate(weekAgo.getDate() - 7);
return lastLogin > weekAgo;
}, 'recent-login-filter');
// Remove specific filter
engineeringView.removeFilter('level-filter');
// Remove all filters
engineeringView.removeFilters();Apply persistent sorting that is maintained as data changes.
/**
* Apply custom sort function to the view
* @param comparefun - Function returning -1, 0, or 1 for comparison
* @returns DynamicView for chaining
*/
applySort(comparefun: (a: object, b: object) => number): DynamicView;
/**
* Apply simple sort by property name
* @param propname - Property name to sort by
* @param options - Sort options (desc: boolean)
* @returns DynamicView for chaining
*/
applySimpleSort(propname: string, options?: { desc?: boolean }): DynamicView;
/**
* Apply compound sort criteria
* @param criteria - Array of [property, isDescending] pairs
* @returns DynamicView for chaining
*/
applySortCriteria(criteria: [string, boolean][]): DynamicView;
/**
* Get current sort configuration
* @returns Current sort criteria
*/
getSort(): any;Usage Examples:
// Simple sort
const usersByName = users.addDynamicView('usersByName')
.applyFind({ active: true })
.applySimpleSort('name');
// Descending sort
const usersByAge = users.addDynamicView('usersByAge')
.applyFind({ active: true })
.applySimpleSort('age', { desc: true });
// Compound sort
const usersByDeptAndName = users.addDynamicView('usersByDeptAndName')
.applyFind({ active: true })
.applySortCriteria([
['department', false], // ascending
['name', false] // ascending
]);
// Custom sort
const usersByNameLength = users.addDynamicView('usersByNameLength')
.applySort((a, b) => a.name.length - b.name.length);Retrieve data from the dynamic view or create resultsets for further operations.
/**
* Get data from the dynamic view
* @param options - Data retrieval options
* @returns Array of documents in the view
*/
data(options?: { removeMeta?: boolean, forceClones?: boolean }): object[];
/**
* Get count of documents in the view
* @returns Number of documents
*/
count(): number;
/**
* Create a branched resultset from the view for additional operations
* @param transform - Transform name to apply
* @param parameters - Transform parameters
* @returns Resultset for further chaining
*/
branchResultset(transform?: string, parameters?: object): Resultset;Usage Examples:
// Get all data from view
const activeUserData = activeUsers.data();
// Get data without metadata
const cleanData = activeUsers.data({ removeMeta: true });
// Get count
const activeCount = activeUsers.count();
// Branch for additional operations
const topActiveUsers = activeUsers.branchResultset()
.simplesort('lastLogin', { desc: true })
.limit(10)
.data();Control view behavior and lifecycle.
/**
* Force rematerialization of the view
* @param options - Rematerialize options
* @returns DynamicView for chaining
*/
rematerialize(options?: { removeWhereFilters?: boolean }): DynamicView;
/**
* Serialize dynamic view to JSON
* @returns JSON representation of the view
*/
toJSON(): string;
/**
* Re-apply all filters to rebuild the view
*/
reapplyFilters(): void;
/**
* Apply generic filter to the view
* @param filter - Filter object with type and parameters
* @returns DynamicView for chaining
*/
applyFilter(filter: object): DynamicView;
/**
* Find index of filter with specific unique identifier
* @param uid - Filter unique identifier
* @returns Index of filter or -1 if not found
*/
_indexOfFilterWithId(uid: string): number;
/**
* Add filter to the view's filter pipeline
* @param filter - Filter object to add
*/
_addFilter(filter: object): void;
/**
* Queue rebuild event for the view
*/
queueRebuildEvent(): void;
/**
* Queue sort phase for the view
*/
queueSortPhase(): void;
/**
* Perform sort phase with options
* @param options - Sort phase options
*/
performSortPhase(options?: object): void;
/**
* Evaluate document for inclusion in view
* @param objIndex - Document index
* @param isNew - Whether document is new
*/
evaluateDocument(objIndex: number, isNew?: boolean): void;
/**
* Remove document from view by index
* @param objIndex - Document index to remove
*/
removeDocument(objIndex: number): void;Usage Examples:
// Force rebuild of view
activeUsers.rematerialize();
// Serialize view configuration
const viewConfig = activeUsers.toJSON();
// Rebuild view filters
activeUsers.reapplyFilters();Dynamic views support transactions for consistent state management.
/**
* Start transaction on the view
* @returns DynamicView for chaining
*/
startTransaction(): DynamicView;
/**
* Commit current transaction
* @returns DynamicView for chaining
*/
commit(): DynamicView;
/**
* Rollback current transaction
* @returns DynamicView for chaining
*/
rollback(): DynamicView;Usage Examples:
// Use transactions for consistent updates
const managersView = users.addDynamicView('managers');
managersView.startTransaction()
.applyFind({ role: 'manager' })
.applySimpleSort('experience', { desc: true });
// Later decide to commit or rollback
if (validationPassed) {
managersView.commit();
} else {
managersView.rollback();
}Perform aggregation operations on dynamic view data.
/**
* Perform map-reduce operation on view data
* @param mapFunction - Map function to apply to each document
* @param reduceFunction - Reduce function to combine results
* @returns Reduced result
*/
mapReduce(mapFunction: (obj: object) => any, reduceFunction: (array: any[]) => any): any;Usage Examples:
// Calculate department statistics from active users view
const deptStats = activeUsers.mapReduce(
obj => ({ [obj.department]: 1 }),
results => {
const counts = {};
results.forEach(result => {
Object.keys(result).forEach(dept => {
counts[dept] = (counts[dept] || 0) + result[dept];
});
});
return counts;
}
);Create complex views with multiple filters and sorting:
const seniorEngineers = users.addDynamicView('seniorEngineers')
.applyFind({ department: 'Engineering' })
.applyFind({ level: { $in: ['Senior', 'Lead', 'Principal'] } })
.applyFind({ active: true })
.applySimpleSort('experience', { desc: true });
// View automatically updates when underlying data changes
users.insert({
name: 'Alice',
department: 'Engineering',
level: 'Senior',
active: true,
experience: 8
});
// Alice will automatically appear in seniorEngineers view
console.log(seniorEngineers.count()); // Increased by 1Use views for frequently accessed data subsets:
// Create views for common queries
const activeCustomers = customers.addDynamicView('active')
.applyFind({ status: 'active' })
.applySimpleSort('lastPurchase', { desc: true });
const vipCustomers = customers.addDynamicView('vip')
.applyFind({ tier: 'VIP', status: 'active' })
.applySimpleSort('totalSpent', { desc: true });
// These views stay current automatically
// No need to re-query when data changesUse dynamic views for live dashboard data:
const todaysSales = orders.addDynamicView('todaysSales')
.applyWhere(obj => {
const today = new Date().toDateString();
const orderDate = new Date(obj.createdAt).toDateString();
return orderDate === today;
})
.applySimpleSort('amount', { desc: true });
// Dashboard always shows current day's sales
setInterval(() => {
const totalSales = todaysSales.data()
.reduce((sum, order) => sum + order.amount, 0);
updateDashboard('todaysSales', totalSales);
}, 1000);Advanced filter pipeline management for dynamic views.
Usage Examples:
// Apply generic filter
const view = users.addDynamicView('customView');
view.applyFilter({
type: 'find',
val: { active: true },
uid: 'active-filter'
});
// Check filter index
const filterIndex = view._indexOfFilterWithId('active-filter');
if (filterIndex !== -1) {
console.log('Filter found at index:', filterIndex);
}
// Manually queue operations
view.queueRebuildEvent();
view.queueSortPhase();Low-level methods for view management and optimization.
Usage Examples:
// These methods are primarily for internal use
// Most applications should use the higher-level methods instead
// Manual sort phase execution
view.performSortPhase({ forceSort: true });
// Document evaluation (called automatically)
view.evaluateDocument(0, true); // Evaluate first document as new
view.removeDocument(5); // Remove document at index 5interface DynamicView {
/** Reference to source collection */
collection: Collection;
/** View name */
name: string;
/** View options */
options: DynamicViewOptions;
/** Filter pipeline array */
filterPipeline: object[];
/** Sort function */
sortFunction: Function;
/** Sort criteria */
sortCriteria: [string, boolean][];
/** Internal resultset */
resultset: Resultset;
/** Result data array */
resultdata: object[];
/** Results dirty flag */
resultsdirty: boolean;
/** Sort dirty flag */
sortDirty: boolean;
/** Rebuild pending flag */
rebuildPending: boolean;
}