0
# Document Operations
1
2
Complete CRUD (Create, Read, Update, Delete) operations for documents in PouchDB, including individual document operations and bulk operations for high-performance scenarios.
3
4
## Capabilities
5
6
### Document Creation and Updates
7
8
Creates new documents or updates existing documents using the PUT method with explicit document IDs.
9
10
```javascript { .api }
11
/**
12
* Create a new document or update an existing document
13
* @param document - Document to create or update (must include _id)
14
* @param options - Options for the put operation
15
* @returns Promise resolving to put result
16
*/
17
db.put(document: Document, options?: PutOptions): Promise<PutResponse>;
18
19
interface Document {
20
_id: string; // Document ID (required)
21
_rev?: string; // Revision ID (for updates)
22
_attachments?: { [name: string]: Attachment }; // Binary attachments
23
_deleted?: boolean; // Deletion marker
24
[key: string]: any; // User-defined fields
25
}
26
27
interface PutOptions {
28
force?: boolean; // Force write without conflict detection
29
}
30
31
interface PutResponse {
32
ok: boolean; // Whether operation succeeded
33
id: string; // Document ID
34
rev: string; // New revision ID
35
}
36
```
37
38
**Usage Examples:**
39
40
```javascript
41
// Create a new document
42
const doc = {
43
_id: 'user123',
44
name: 'Alice Smith',
45
email: 'alice@example.com',
46
created: new Date().toISOString()
47
};
48
49
const response = await db.put(doc);
50
console.log('Document created:', response.id, response.rev);
51
52
// Update an existing document
53
const existingDoc = await db.get('user123');
54
existingDoc.email = 'alice.smith@example.com';
55
existingDoc.updated = new Date().toISOString();
56
57
const updateResponse = await db.put(existingDoc);
58
console.log('Document updated:', updateResponse.rev);
59
```
60
61
### Document Creation with Auto-Generated IDs
62
63
Creates new documents with automatically generated IDs using the POST method.
64
65
```javascript { .api }
66
/**
67
* Create a new document with auto-generated ID
68
* @param document - Document to create (no _id required)
69
* @param options - Options for the post operation
70
* @returns Promise resolving to post result
71
*/
72
db.post(document: Omit<Document, '_id'>, options?: PostOptions): Promise<PostResponse>;
73
74
interface PostOptions {
75
[key: string]: any; // Additional options
76
}
77
78
interface PostResponse {
79
ok: boolean; // Whether operation succeeded
80
id: string; // Auto-generated document ID
81
rev: string; // New revision ID
82
}
83
```
84
85
**Usage Examples:**
86
87
```javascript
88
// Create document with auto-generated ID
89
const newDoc = {
90
type: 'note',
91
title: 'Meeting Notes',
92
content: 'Discussed project timeline and deliverables',
93
created: new Date().toISOString()
94
};
95
96
const response = await db.post(newDoc);
97
console.log('Document created with ID:', response.id);
98
```
99
100
### Document Retrieval
101
102
Retrieves documents by ID with various options for including metadata, attachments, and revision information.
103
104
```javascript { .api }
105
/**
106
* Retrieve a document by ID
107
* @param docId - Document ID to retrieve
108
* @param options - Options for document retrieval
109
* @returns Promise resolving to the document
110
*/
111
db.get(docId: string, options?: GetOptions): Promise<Document>;
112
113
interface GetOptions {
114
rev?: string; // Retrieve specific revision
115
revs?: boolean; // Include revision history
116
revs_info?: boolean; // Include revision info with status
117
conflicts?: boolean; // Include conflicting revisions
118
attachments?: boolean; // Include attachment data
119
binary?: boolean; // Get attachments as binary instead of base64
120
}
121
```
122
123
**Usage Examples:**
124
125
```javascript
126
// Get a document by ID
127
const doc = await db.get('user123');
128
console.log('User name:', doc.name);
129
130
// Get specific revision
131
const oldVersion = await db.get('user123', { rev: '2-abc123' });
132
133
// Get document with revision history
134
const docWithHistory = await db.get('user123', {
135
revs: true,
136
revs_info: true
137
});
138
console.log('Revision history:', docWithHistory._revisions);
139
140
// Get document with attachments
141
const docWithAttachments = await db.get('user123', {
142
attachments: true
143
});
144
```
145
146
### Document Deletion
147
148
Removes documents from the database. Documents are not physically deleted but marked as deleted.
149
150
```javascript { .api }
151
/**
152
* Delete a document
153
* @param document - Document to delete or document ID
154
* @param options - Options for the remove operation
155
* @returns Promise resolving to remove result
156
*/
157
db.remove(document: Document | string, options?: RemoveOptions): Promise<RemoveResponse>;
158
159
interface RemoveOptions {
160
[key: string]: any; // Additional options
161
}
162
163
interface RemoveResponse {
164
ok: boolean; // Whether operation succeeded
165
id: string; // Document ID
166
rev: string; // New revision ID (deletion marker)
167
}
168
```
169
170
**Usage Examples:**
171
172
```javascript
173
// Delete using document object
174
const doc = await db.get('user123');
175
const response = await db.remove(doc);
176
console.log('Document deleted:', response.id);
177
178
// Delete using document ID and revision
179
const response = await db.remove('user123', '3-def456');
180
181
// Alternative syntax with document object
182
await db.remove({
183
_id: 'user123',
184
_rev: '3-def456'
185
});
186
```
187
188
### Bulk Document Operations
189
190
Performs multiple document operations in a single request for improved performance.
191
192
```javascript { .api }
193
/**
194
* Perform bulk document operations (create, update, delete)
195
* @param documents - Array of documents to process
196
* @param options - Options for bulk operations
197
* @returns Promise resolving to array of bulk results
198
*/
199
db.bulkDocs(documents: Document[], options?: BulkDocsOptions): Promise<BulkResponse[]>;
200
201
interface BulkDocsOptions {
202
new_edits?: boolean; // Whether to generate new revision IDs
203
[key: string]: any; // Additional options
204
}
205
206
interface BulkResponse {
207
ok?: boolean; // Whether operation succeeded
208
id: string; // Document ID
209
rev?: string; // New revision ID (if successful)
210
error?: string; // Error type (if failed)
211
reason?: string; // Error reason (if failed)
212
}
213
```
214
215
**Usage Examples:**
216
217
```javascript
218
// Bulk create/update documents
219
const docs = [
220
{ _id: 'user1', name: 'Alice', type: 'user' },
221
{ _id: 'user2', name: 'Bob', type: 'user' },
222
{ _id: 'user3', name: 'Charlie', type: 'user' }
223
];
224
225
const results = await db.bulkDocs(docs);
226
results.forEach(result => {
227
if (result.ok) {
228
console.log(`Document ${result.id} saved with rev ${result.rev}`);
229
} else {
230
console.error(`Failed to save ${result.id}: ${result.error}`);
231
}
232
});
233
234
// Bulk delete documents (set _deleted: true)
235
const existingDocs = await Promise.all([
236
db.get('user1'),
237
db.get('user2')
238
]);
239
240
const docsToDelete = existingDocs.map(doc => ({
241
...doc,
242
_deleted: true
243
}));
244
245
await db.bulkDocs(docsToDelete);
246
```
247
248
### Retrieve All Documents
249
250
Retrieves multiple documents with options for pagination, filtering, and including document content.
251
252
```javascript { .api }
253
/**
254
* Retrieve all documents in the database
255
* @param options - Options for document retrieval
256
* @returns Promise resolving to all documents result
257
*/
258
db.allDocs(options?: AllDocsOptions): Promise<AllDocsResponse>;
259
260
interface AllDocsOptions {
261
include_docs?: boolean; // Include full document content
262
startkey?: string; // Start key for range queries
263
endkey?: string; // End key for range queries
264
limit?: number; // Maximum number of documents
265
skip?: number; // Number of documents to skip
266
descending?: boolean; // Reverse sort order
267
keys?: string[]; // Specific document IDs to retrieve
268
}
269
270
interface AllDocsResponse {
271
total_rows: number; // Total number of documents
272
offset: number; // Starting offset
273
rows: AllDocsRow[]; // Array of document rows
274
}
275
276
interface AllDocsRow {
277
id: string; // Document ID
278
key: string; // Sort key (same as ID)
279
value: { rev: string }; // Document metadata
280
doc?: Document; // Full document (if include_docs: true)
281
}
282
```
283
284
**Usage Examples:**
285
286
```javascript
287
// Get all documents with content
288
const result = await db.allDocs({ include_docs: true });
289
result.rows.forEach(row => {
290
console.log(`${row.id}: ${row.doc.name}`);
291
});
292
293
// Paginated retrieval
294
const page1 = await db.allDocs({
295
limit: 10,
296
include_docs: true
297
});
298
299
const page2 = await db.allDocs({
300
limit: 10,
301
skip: 10,
302
include_docs: true
303
});
304
305
// Range query
306
const userDocs = await db.allDocs({
307
startkey: 'user_',
308
endkey: 'user_\ufff0',
309
include_docs: true
310
});
311
312
// Get specific documents
313
const specificDocs = await db.allDocs({
314
keys: ['user1', 'user2', 'user3'],
315
include_docs: true
316
});
317
```
318
319
### Document Purging
320
321
Permanently removes document revisions from the database (advanced operation).
322
323
```javascript { .api }
324
/**
325
* Permanently purge a document revision
326
* @param docId - Document ID to purge
327
* @param rev - Revision ID to purge
328
* @returns Promise resolving when purge is complete
329
*/
330
db.purge(docId: string, rev: string): Promise<void>;
331
```
332
333
**Usage Examples:**
334
335
```javascript
336
// Purge a specific document revision
337
await db.purge('user123', '1-abc123');
338
console.log('Document revision purged permanently');
339
```
340
341
## Error Handling
342
343
Document operations can fail for various reasons. Handle errors appropriately:
344
345
```javascript
346
try {
347
const doc = await db.get('nonexistent');
348
} catch (error) {
349
if (error.status === 404) {
350
console.log('Document not found');
351
} else if (error.status === 409) {
352
console.log('Document update conflict');
353
} else {
354
console.log('Unexpected error:', error.message);
355
}
356
}
357
```
358
359
Common error codes:
360
- `404` - Document not found
361
- `409` - Document update conflict
362
- `400` - Bad request (invalid document)
363
- `401` - Authentication required
364
- `403` - Permission denied