0
# Database Operations
1
2
Core CRUD operations for document management in PouchDB, including creation, retrieval, updates, and deletion with comprehensive conflict resolution and error handling.
3
4
## Capabilities
5
6
### Database Constructor
7
8
#### PouchDB()
9
10
Creates a new PouchDB database instance with automatic adapter selection.
11
12
```javascript { .api }
13
/**
14
* Create a new PouchDB database instance
15
* @param name - Database name (for local databases) or URL (for remote databases)
16
* @param options - Configuration options for the database
17
*/
18
function PouchDB(name, options);
19
```
20
21
**Usage Examples:**
22
23
```javascript
24
// Local database (uses IndexedDB in browser, LevelDB in Node.js)
25
const localDB = new PouchDB('my-local-database');
26
27
// Remote database
28
const remoteDB = new PouchDB('https://example.com/my-remote-db');
29
30
// Database with custom options
31
const customDB = new PouchDB('my-db', {
32
adapter: 'memory',
33
auto_compaction: true
34
});
35
36
// Database with authentication
37
const authDB = new PouchDB('https://user:pass@example.com/secure-db');
38
```
39
40
### Document Creation
41
42
#### db.put()
43
44
Creates a new document or updates an existing document with a specified ID.
45
46
```javascript { .api }
47
/**
48
* Create or update a document
49
* @param doc - Document object, must include _id and optionally _rev for updates
50
* @param options - Optional configuration parameters
51
* @param callback - Optional callback function (err, response) => void
52
* @returns Promise resolving to DocumentResponse
53
*/
54
db.put(doc, options, callback);
55
```
56
57
**Usage Examples:**
58
59
```javascript
60
// Create a new document
61
const response = await db.put({
62
_id: 'user_001',
63
name: 'Alice Johnson',
64
email: 'alice@example.com',
65
active: true
66
});
67
console.log(response.id, response.rev); // user_001, 1-abc123...
68
69
// Update an existing document
70
const existingDoc = await db.get('user_001');
71
const updateResponse = await db.put({
72
...existingDoc,
73
email: 'alice.johnson@example.com',
74
updated: new Date().toISOString()
75
});
76
77
// Create with batch option for better performance
78
await db.put({
79
_id: 'batch_doc',
80
data: 'some data'
81
}, { batch: 'ok' });
82
```
83
84
#### db.post()
85
86
Creates a new document with an auto-generated ID.
87
88
```javascript { .api }
89
/**
90
* Create a new document with auto-generated ID
91
* @param doc - Document object without _id (ID will be generated)
92
* @param options - Optional configuration parameters
93
* @param callback - Optional callback function (err, response) => void
94
* @returns Promise resolving to DocumentResponse with generated ID
95
*/
96
db.post(doc, options, callback);
97
```
98
99
**Usage Examples:**
100
101
```javascript
102
// Create document with auto-generated ID
103
const response = await db.post({
104
type: 'log-entry',
105
message: 'User logged in',
106
timestamp: new Date().toISOString()
107
});
108
console.log(response.id); // Auto-generated ID like "7f2ac1a4-..."
109
110
// Batch create for performance
111
await db.post({
112
type: 'analytics',
113
event: 'page_view'
114
}, { batch: 'ok' });
115
```
116
117
### Document Retrieval
118
119
#### db.get()
120
121
Retrieves a document by its ID.
122
123
```javascript { .api }
124
/**
125
* Retrieve a document by ID
126
* @param docId - Document identifier
127
* @param options - Optional retrieval parameters
128
* @param callback - Optional callback function (err, doc) => void
129
* @returns Promise resolving to document object
130
*/
131
db.get(docId, options, callback);
132
```
133
134
**Usage Examples:**
135
136
```javascript
137
// Basic document retrieval
138
const doc = await db.get('user_001');
139
console.log(doc.name, doc.email);
140
141
// Get specific revision
142
const oldDoc = await db.get('user_001', {
143
rev: '1-abc123def456'
144
});
145
146
// Get with revision history
147
const docWithRevs = await db.get('user_001', {
148
revs: true,
149
revs_info: true
150
});
151
152
// Get with attachment metadata
153
const docWithAttachments = await db.get('user_001', {
154
attachments: true
155
});
156
```
157
158
### Document Deletion
159
160
#### db.remove()
161
162
Deletes a document from the database.
163
164
```javascript { .api }
165
/**
166
* Delete a document
167
* @param docOrId - Document object (with _id and _rev) or document ID string
168
* @param optsOrRev - Options object or revision string
169
* @param opts - Additional options when second parameter is revision string
170
* @param callback - Optional callback function (err, response) => void
171
* @returns Promise resolving to DocumentResponse
172
*/
173
db.remove(docOrId, optsOrRev, opts, callback);
174
```
175
176
**Usage Examples:**
177
178
```javascript
179
// Delete using document object
180
const doc = await db.get('user_001');
181
const response = await db.remove(doc);
182
183
// Delete using ID and revision
184
const response = await db.remove('user_001', '2-def456ghi789');
185
186
// Delete with options
187
await db.remove('user_001', '2-def456ghi789', { batch: 'ok' });
188
189
// Alternative syntax with options object
190
await db.remove({
191
_id: 'user_001',
192
_rev: '2-def456ghi789'
193
});
194
```
195
196
### Database Information
197
198
#### db.info()
199
200
Retrieves information about the database.
201
202
```javascript { .api }
203
/**
204
* Get database information
205
* @param callback - Optional callback function (err, info) => void
206
* @returns Promise resolving to database info object
207
*/
208
db.info(callback);
209
```
210
211
**Usage Examples:**
212
213
```javascript
214
const info = await db.info();
215
console.log(info);
216
// Output example:
217
// {
218
// "db_name": "my-database",
219
// "doc_count": 42,
220
// "update_seq": 123,
221
// "adapter": "idb",
222
// "auto_compaction": false
223
// }
224
```
225
226
### Database Management
227
228
#### db.destroy()
229
230
Permanently deletes the entire database.
231
232
```javascript { .api }
233
/**
234
* Delete the entire database
235
* @param options - Optional destruction parameters
236
* @param callback - Optional callback function (err, response) => void
237
* @returns Promise resolving to operation result
238
*/
239
db.destroy(options, callback);
240
```
241
242
**Usage Examples:**
243
244
```javascript
245
// Destroy database
246
await db.destroy();
247
console.log('Database destroyed');
248
249
// Destroy with callback
250
db.destroy((err, response) => {
251
if (err) {
252
console.error('Failed to destroy database:', err);
253
} else {
254
console.log('Database destroyed successfully');
255
}
256
});
257
```
258
259
#### db.close()
260
261
Closes the database connection.
262
263
```javascript { .api }
264
/**
265
* Close the database connection
266
* @param callback - Optional callback function (err) => void
267
* @returns Promise resolving when database is closed
268
*/
269
db.close(callback);
270
```
271
272
**Usage Examples:**
273
274
```javascript
275
// Close database
276
await db.close();
277
console.log('Database closed');
278
279
// Close with callback
280
db.close((err) => {
281
if (err) {
282
console.error('Error closing database:', err);
283
} else {
284
console.log('Database closed successfully');
285
}
286
});
287
```
288
289
#### db.compact()
290
291
Compacts the database to reduce storage space.
292
293
```javascript { .api }
294
/**
295
* Compact the database to reduce storage space
296
* @param options - Optional compaction parameters
297
* @param callback - Optional callback function (err, response) => void
298
* @returns Promise resolving to compaction result
299
*/
300
db.compact(options, callback);
301
```
302
303
**Usage Examples:**
304
305
```javascript
306
// Basic compaction
307
await db.compact();
308
console.log('Database compacted');
309
310
// Compact with options
311
await db.compact({
312
interval: 300 // Compact every 300ms
313
});
314
```
315
316
## Response Objects
317
318
### DocumentResponse
319
320
```javascript { .api }
321
interface DocumentResponse {
322
/** Indicates operation success */
323
ok: boolean;
324
325
/** Document ID */
326
id: string;
327
328
/** New revision identifier */
329
rev: string;
330
}
331
```
332
333
### DatabaseInfo
334
335
```javascript { .api }
336
interface DatabaseInfo {
337
/** Database name */
338
db_name: string;
339
340
/** Number of documents in database */
341
doc_count: number;
342
343
/** Current update sequence number */
344
update_seq: number | string;
345
346
/** Database adapter being used */
347
adapter: string;
348
349
/** Whether auto-compaction is enabled */
350
auto_compaction: boolean;
351
352
/** Additional adapter-specific information */
353
[key: string]: any;
354
}
355
```
356
357
## Options Objects
358
359
### PouchDBOptions
360
361
```javascript { .api }
362
interface PouchDBOptions {
363
/** Specific adapter to use ('idb', 'leveldb', 'http', 'memory', etc.) */
364
adapter?: string;
365
366
/** Enable automatic compaction */
367
auto_compaction?: boolean;
368
369
/** Prefix for database names */
370
prefix?: string;
371
372
/** Database name (alternative to first parameter) */
373
name?: string;
374
375
/** Authentication credentials for remote databases */
376
auth?: {
377
username: string;
378
password: string;
379
};
380
381
/** Custom HTTP headers for remote databases */
382
headers?: { [key: string]: string };
383
384
/** Request timeout for remote databases (milliseconds) */
385
timeout?: number;
386
387
/** Skip setup of the database */
388
skip_setup?: boolean;
389
390
/** Additional adapter-specific options */
391
[key: string]: any;
392
}
393
```
394
395
### GetOptions
396
397
```javascript { .api }
398
interface GetOptions {
399
/** Specific revision to retrieve */
400
rev?: string;
401
402
/** Include revision history */
403
revs?: boolean;
404
405
/** Include detailed revision information */
406
revs_info?: boolean;
407
408
/** Open specific revisions */
409
open_revs?: string[] | 'all';
410
411
/** Include attachment data */
412
attachments?: boolean;
413
414
/** Return attachments as binary */
415
binary?: boolean;
416
417
/** Include conflicts array */
418
conflicts?: boolean;
419
420
/** Additional retrieval options */
421
[key: string]: any;
422
}
423
```
424
425
### PutOptions
426
427
```javascript { .api }
428
interface PutOptions {
429
/** Force new document creation (don't update existing) */
430
new_edits?: boolean;
431
432
/** Batch mode for better performance */
433
batch?: 'ok';
434
435
/** Additional creation options */
436
[key: string]: any;
437
}
438
```
439
440
## Error Handling
441
442
### Common Error Types
443
444
```javascript { .api }
445
interface PouchDBError {
446
/** HTTP-style status code */
447
status: number;
448
449
/** Error name/type */
450
name: string;
451
452
/** Human-readable error message */
453
message: string;
454
455
/** Indicates this is a PouchDB error */
456
error: boolean;
457
458
/** Additional error details */
459
reason?: string;
460
}
461
```
462
463
### Error Handling Examples
464
465
```javascript
466
try {
467
const doc = await db.get('nonexistent-doc');
468
} catch (err) {
469
if (err.status === 404) {
470
console.log('Document not found');
471
} else {
472
console.error('Unexpected error:', err);
473
}
474
}
475
476
// Handle conflicts during updates
477
try {
478
await db.put({
479
_id: 'user_001',
480
_rev: 'old-revision',
481
name: 'Updated Name'
482
});
483
} catch (err) {
484
if (err.status === 409) {
485
console.log('Conflict - document was updated by someone else');
486
// Fetch latest version and retry
487
const latestDoc = await db.get('user_001');
488
await db.put({
489
...latestDoc,
490
name: 'Updated Name'
491
});
492
}
493
}
494
495
// Handle network errors for remote databases
496
try {
497
const remoteDB = new PouchDB('https://example.com/db');
498
await remoteDB.info();
499
} catch (err) {
500
if (err.status === 401) {
501
console.error('Authentication required');
502
} else if (err.status === 0) {
503
console.error('Network error - server unreachable');
504
} else {
505
console.error('Database error:', err.message);
506
}
507
}
508
```
509
510
## Advanced Patterns
511
512
### Document Versioning
513
514
```javascript
515
// Safe document update with conflict resolution
516
async function safeUpdate(db, docId, updateFn) {
517
try {
518
const doc = await db.get(docId);
519
const updatedDoc = updateFn(doc);
520
return await db.put(updatedDoc);
521
} catch (err) {
522
if (err.status === 409) {
523
// Conflict - retry with latest version
524
return safeUpdate(db, docId, updateFn);
525
}
526
throw err;
527
}
528
}
529
530
// Usage
531
await safeUpdate(db, 'user_001', (doc) => ({
532
...doc,
533
lastLogin: new Date().toISOString()
534
}));
535
```
536
537
### Batch Operations with Individual Error Handling
538
539
```javascript
540
// Process multiple documents with individual error handling
541
const documents = [
542
{ _id: 'doc1', data: 'value1' },
543
{ _id: 'doc2', data: 'value2' },
544
{ _id: 'doc3', data: 'value3' }
545
];
546
547
const results = await Promise.allSettled(
548
documents.map(doc => db.put(doc))
549
);
550
551
results.forEach((result, index) => {
552
if (result.status === 'fulfilled') {
553
console.log(`Document ${documents[index]._id} saved:`, result.value);
554
} else {
555
console.error(`Document ${documents[index]._id} failed:`, result.reason);
556
}
557
});
558
```