0
# Database Management
1
2
Core database operations for creating, configuring, and managing LokiJS database instances with persistence and serialization capabilities.
3
4
## Capabilities
5
6
### Database Constructor
7
8
Creates a new LokiJS database instance with optional configuration.
9
10
```javascript { .api }
11
/**
12
* Creates a new LokiJS database instance
13
* @param filename - Optional filename for persistence
14
* @param options - Database configuration options
15
*/
16
constructor Loki(filename?: string, options?: DatabaseOptions);
17
18
interface DatabaseOptions {
19
/** Enable automatic saving at intervals */
20
autosave?: boolean;
21
/** Autosave interval in milliseconds */
22
autosaveInterval?: number;
23
/** Persistence adapter for storage operations */
24
adapter?: PersistenceAdapter;
25
/** Serialization method ('normal', 'pretty', 'destructured') */
26
serializationMethod?: string;
27
/** Delimiter for destructured serialization */
28
destructureDelimiter?: string;
29
/** Enable verbose logging */
30
verbose?: boolean;
31
/** Throttled saves configuration */
32
throttledSaves?: boolean;
33
}
34
```
35
36
**Usage Examples:**
37
38
```javascript
39
// Basic database
40
const db = new loki();
41
42
// Database with filename
43
const db = new loki('myapp.db');
44
45
// Database with options
46
const db = new loki('myapp.db', {
47
autosave: true,
48
autosaveInterval: 4000,
49
adapter: new loki.LokiFsAdapter(),
50
verbose: true
51
});
52
```
53
54
### Collection Management
55
56
Add, retrieve, and manage collections within the database.
57
58
```javascript { .api }
59
/**
60
* Add a collection to the database
61
* @param name - Collection name
62
* @param options - Collection configuration options
63
* @returns The created collection
64
*/
65
addCollection(name: string, options?: CollectionOptions): Collection;
66
67
/**
68
* Retrieve a collection by name
69
* @param collectionName - Name of the collection
70
* @returns Collection instance or null if not found
71
*/
72
getCollection(collectionName: string): Collection | null;
73
74
/**
75
* Remove a collection from the database
76
* @param collectionName - Name of collection to remove
77
*/
78
removeCollection(collectionName: string): void;
79
80
/**
81
* Rename an existing collection
82
* @param oldName - Current collection name
83
* @param newName - New collection name
84
*/
85
renameCollection(oldName: string, newName: string): void;
86
87
/**
88
* Get list of all collection names
89
* @returns Array of collection names
90
*/
91
listCollections(): string[];
92
```
93
94
**Usage Examples:**
95
96
```javascript
97
// Add collections
98
const users = db.addCollection('users');
99
const orders = db.addCollection('orders', {
100
unique: ['orderId'],
101
indices: ['customerId']
102
});
103
104
// Get existing collection
105
const users = db.getCollection('users');
106
107
// List all collections
108
const collections = db.listCollections();
109
console.log(collections); // ['users', 'orders']
110
111
// Rename collection
112
db.renameCollection('users', 'customers');
113
114
// Remove collection
115
db.removeCollection('orders');
116
```
117
118
### Database Persistence
119
120
Load and save database state using configured persistence adapters.
121
122
```javascript { .api }
123
/**
124
* Load database from storage
125
* @param options - Load options
126
* @param callback - Completion callback
127
*/
128
loadDatabase(options?: any, callback?: (err?: Error) => void): void;
129
130
/**
131
* Save database to storage
132
* @param callback - Completion callback
133
*/
134
saveDatabase(callback?: (err?: Error) => void): void;
135
136
/**
137
* Delete database from storage
138
* @param options - Delete options
139
* @param callback - Completion callback
140
*/
141
deleteDatabase(options?: any, callback?: (err?: Error) => void): void;
142
```
143
144
**Usage Examples:**
145
146
```javascript
147
// Load database
148
db.loadDatabase({}, (err) => {
149
if (err) {
150
console.error('Failed to load database:', err);
151
} else {
152
console.log('Database loaded successfully');
153
}
154
});
155
156
// Save database
157
db.saveDatabase((err) => {
158
if (err) {
159
console.error('Failed to save database:', err);
160
} else {
161
console.log('Database saved successfully');
162
}
163
});
164
165
// Delete database
166
db.deleteDatabase({}, (err) => {
167
if (err) {
168
console.error('Failed to delete database:', err);
169
} else {
170
console.log('Database deleted successfully');
171
}
172
});
173
```
174
175
### Serialization
176
177
Convert database to and from JSON for storage or transport.
178
179
```javascript { .api }
180
/**
181
* Serialize database to JSON string
182
* @param options - Serialization options
183
* @returns JSON string representation
184
*/
185
serialize(options?: SerializeOptions): string;
186
187
/**
188
* Serialize using destructured format
189
* @param options - Serialization options
190
* @returns Destructured JSON representation
191
*/
192
serializeDestructured(options?: SerializeOptions): string;
193
194
/**
195
* Load database from JSON string
196
* @param serializedDb - JSON string of database
197
* @param options - Load options
198
*/
199
loadJSON(serializedDb: string, options?: any): void;
200
201
/**
202
* Load database from JSON object
203
* @param dbObject - Database object
204
* @param options - Load options
205
*/
206
loadJSONObject(dbObject: object, options?: any): void;
207
208
interface SerializeOptions {
209
/** Serialization method ('normal', 'pretty', 'destructured') */
210
serializationMethod?: string;
211
/** Delimiter for destructured serialization */
212
destructureDelimiter?: string;
213
/** Collections to include in serialization */
214
partitioned?: boolean;
215
}
216
```
217
218
**Usage Examples:**
219
220
```javascript
221
// Serialize database
222
const jsonString = db.serialize();
223
224
// Serialize with pretty formatting
225
const prettyJson = db.serialize({
226
serializationMethod: 'pretty'
227
});
228
229
// Load from JSON string
230
const newDb = new loki();
231
newDb.loadJSON(jsonString);
232
233
// Load from object
234
const dbObject = JSON.parse(jsonString);
235
newDb.loadJSONObject(dbObject);
236
```
237
238
### Auto-save Configuration
239
240
Configure automatic database persistence at regular intervals.
241
242
```javascript { .api }
243
/**
244
* Enable auto-save functionality
245
* @param options - Auto-save configuration
246
* @param callback - Save completion callback
247
*/
248
autosaveEnable(options?: AutosaveOptions, callback?: Function): void;
249
250
/**
251
* Disable auto-save functionality
252
*/
253
autosaveDisable(): void;
254
255
/**
256
* Check if auto-save is needed
257
* @returns True if database needs saving
258
*/
259
autosaveDirty(): boolean;
260
261
interface AutosaveOptions {
262
/** Auto-save interval in milliseconds */
263
autosaveInterval?: number;
264
/** Save callback function */
265
saveCallback?: Function;
266
}
267
```
268
269
**Usage Examples:**
270
271
```javascript
272
// Enable auto-save every 5 seconds
273
db.autosaveEnable({
274
autosaveInterval: 5000,
275
saveCallback: (err) => {
276
if (err) {
277
console.error('Auto-save failed:', err);
278
}
279
}
280
});
281
282
// Check if save is needed
283
if (db.autosaveDirty()) {
284
console.log('Database has unsaved changes');
285
}
286
287
// Disable auto-save
288
db.autosaveDisable();
289
```
290
291
### Database Information
292
293
Retrieve metadata and configuration information about the database.
294
295
```javascript { .api }
296
/**
297
* Get database name
298
* @returns Database filename
299
*/
300
getName(): string;
301
302
/**
303
* Create a copy of the database
304
* @param options - Copy options
305
* @returns New database instance
306
*/
307
copy(options?: any): Loki;
308
309
/**
310
* Close the database
311
* @param callback - Close completion callback
312
*/
313
close(callback?: Function): void;
314
```
315
316
**Usage Examples:**
317
318
```javascript
319
// Get database name
320
const name = db.getName();
321
console.log('Database name:', name);
322
323
// Create database copy
324
const dbCopy = db.copy();
325
326
// Close database
327
db.close(() => {
328
console.log('Database closed');
329
});
330
```
331
332
### Changes API
333
334
Track and manage document changes across collections.
335
336
```javascript { .api }
337
/**
338
* Generate changes notification for specified collections
339
* @param arrayOfCollectionNames - Array of collection names to generate changes for
340
* @returns Object containing changes data
341
*/
342
generateChangesNotification(arrayOfCollectionNames: string[]): object;
343
344
/**
345
* Serialize changes for specified collections to JSON string
346
* @param collectionNamesArray - Array of collection names
347
* @returns JSON string of changes
348
*/
349
serializeChanges(collectionNamesArray: string[]): string;
350
351
/**
352
* Clear all changes in all collections
353
*/
354
clearChanges(): void;
355
```
356
357
**Usage Examples:**
358
359
```javascript
360
// Enable changes tracking when creating collections
361
const users = db.addCollection('users', {
362
disableChangesApi: false
363
});
364
365
// Make some changes
366
users.insert({ name: 'Alice', age: 25 });
367
users.insert({ name: 'Bob', age: 30 });
368
369
// Get changes for specific collections
370
const changes = db.generateChangesNotification(['users']);
371
console.log('Changes:', changes);
372
373
// Serialize changes to JSON
374
const changesJson = db.serializeChanges(['users']);
375
376
// Clear all changes
377
db.clearChanges();
378
```
379
380
### Advanced Serialization
381
382
Specialized serialization methods for different use cases.
383
384
```javascript { .api }
385
/**
386
* Serialize database using destructured format
387
* @param options - Destructured serialization options
388
* @returns Destructured representation
389
*/
390
serializeDestructured(options?: DestructuredOptions): string | any[];
391
392
/**
393
* Serialize individual collection
394
* @param options - Collection serialization options
395
* @returns Serialized collection data
396
*/
397
serializeCollection(options: CollectionSerializeOptions): string | any[];
398
399
/**
400
* Deserialize destructured database format
401
* @param destructuredSource - Destructured data source
402
* @param options - Deserialization options
403
* @returns Database object representation
404
*/
405
deserializeDestructured(destructuredSource: any, options?: any): object;
406
407
/**
408
* Deserialize individual collection data
409
* @param destructuredSource - Collection data source
410
* @param options - Deserialization options
411
* @returns Array of documents
412
*/
413
deserializeCollection(destructuredSource: any, options?: any): object[];
414
415
/**
416
* Alias for serialize method
417
* @param options - Serialization options
418
* @returns JSON string representation
419
*/
420
toJson(options?: SerializeOptions): string;
421
422
interface DestructuredOptions {
423
/** Enable delimited format */
424
delimited?: boolean;
425
/** Custom delimiter string */
426
delimiter?: string;
427
/** Enable partitioned format */
428
partitioned?: boolean;
429
/** Specific partition to serialize */
430
partition?: number;
431
}
432
433
interface CollectionSerializeOptions {
434
/** Enable delimited format */
435
delimited?: boolean;
436
/** Custom delimiter string */
437
delimiter?: string;
438
/** Collection index to serialize */
439
collectionIndex: number;
440
}
441
```
442
443
**Usage Examples:**
444
445
```javascript
446
// Destructured serialization for large databases
447
const destructured = db.serializeDestructured({
448
delimited: true,
449
delimiter: '|'
450
});
451
452
// Serialize individual collection
453
const collectionData = db.serializeCollection({
454
collectionIndex: 0,
455
delimited: true
456
});
457
458
// Use toJson alias
459
const jsonString = db.toJson({ serializationMethod: 'pretty' });
460
461
// Deserialize destructured format
462
const dbObject = db.deserializeDestructured(destructured);
463
const newDb = new loki();
464
newDb.loadJSONObject(dbObject);
465
```
466
467
### Internal Methods
468
469
Low-level methods for advanced usage and adapter development.
470
471
```javascript { .api }
472
/**
473
* Load collection object into database
474
* @param collection - Collection object to load
475
*/
476
loadCollection(collection: object): void;
477
478
/**
479
* Configure database options
480
* @param options - Configuration options
481
* @param initialConfig - Whether this is initial configuration
482
*/
483
configureOptions(options: DatabaseOptions, initialConfig?: boolean): void;
484
485
/**
486
* Get indexed adapter for browserify compatibility
487
* @returns Indexed adapter if available
488
*/
489
getIndexedAdapter(): any;
490
491
/**
492
* Internal serialization replacer function
493
* @param key - Property key
494
* @param value - Property value
495
* @returns Modified value or undefined to exclude
496
*/
497
serializeReplacer(key: string, value: any): any;
498
499
/**
500
* Internal save method without throttling
501
* @param callback - Completion callback
502
*/
503
saveDatabaseInternal(callback?: (err?: Error) => void): void;
504
505
/**
506
* Internal load method without throttling
507
* @param options - Load options
508
* @param callback - Completion callback
509
*/
510
loadDatabaseInternal(options?: any, callback?: (err?: Error) => void): void;
511
512
/**
513
* Drain throttled save queue
514
* @param callback - Completion callback
515
* @param options - Drain options
516
*/
517
throttledSaveDrain(callback: Function, options?: object): void;
518
519
/**
520
* Clear autosave flags after successful save
521
*/
522
autosaveClearFlags(): void;
523
```
524
525
**Usage Examples:**
526
527
```javascript
528
// These methods are primarily for internal use
529
// Most applications should use the higher-level methods instead
530
531
// Example: Custom adapter development might use internal methods
532
db.saveDatabaseInternal((err) => {
533
if (err) {
534
console.error('Internal save failed:', err);
535
}
536
});
537
```
538
539
## Properties
540
541
```javascript { .api }
542
interface Loki {
543
/** Database filename */
544
filename: string;
545
/** Array of collections */
546
collections: Collection[];
547
/** Database version */
548
databaseVersion: number;
549
/** Engine version */
550
engineVersion: number;
551
/** Auto-save enabled flag */
552
autosave: boolean;
553
/** Auto-save interval in milliseconds */
554
autosaveInterval: number;
555
/** Database options */
556
options: DatabaseOptions;
557
/** Persistence adapter instance */
558
persistenceAdapter: PersistenceAdapter;
559
/** Verbose logging flag */
560
verbose: boolean;
561
}
562
```