Core CRUD operations for document management in PouchDB, including creation, retrieval, updates, and deletion with comprehensive conflict resolution and error handling.
Creates a new PouchDB database instance with automatic adapter selection.
/**
* Create a new PouchDB database instance
* @param name - Database name (for local databases) or URL (for remote databases)
* @param options - Configuration options for the database
*/
function PouchDB(name, options);Usage Examples:
// Local database (uses IndexedDB in browser, LevelDB in Node.js)
const localDB = new PouchDB('my-local-database');
// Remote database
const remoteDB = new PouchDB('https://example.com/my-remote-db');
// Database with custom options
const customDB = new PouchDB('my-db', {
adapter: 'memory',
auto_compaction: true
});
// Database with authentication
const authDB = new PouchDB('https://user:pass@example.com/secure-db');Creates a new document or updates an existing document with a specified ID.
/**
* Create or update a document
* @param doc - Document object, must include _id and optionally _rev for updates
* @param options - Optional configuration parameters
* @param callback - Optional callback function (err, response) => void
* @returns Promise resolving to DocumentResponse
*/
db.put(doc, options, callback);Usage Examples:
// Create a new document
const response = await db.put({
_id: 'user_001',
name: 'Alice Johnson',
email: 'alice@example.com',
active: true
});
console.log(response.id, response.rev); // user_001, 1-abc123...
// Update an existing document
const existingDoc = await db.get('user_001');
const updateResponse = await db.put({
...existingDoc,
email: 'alice.johnson@example.com',
updated: new Date().toISOString()
});
// Create with batch option for better performance
await db.put({
_id: 'batch_doc',
data: 'some data'
}, { batch: 'ok' });Creates a new document with an auto-generated ID.
/**
* Create a new document with auto-generated ID
* @param doc - Document object without _id (ID will be generated)
* @param options - Optional configuration parameters
* @param callback - Optional callback function (err, response) => void
* @returns Promise resolving to DocumentResponse with generated ID
*/
db.post(doc, options, callback);Usage Examples:
// Create document with auto-generated ID
const response = await db.post({
type: 'log-entry',
message: 'User logged in',
timestamp: new Date().toISOString()
});
console.log(response.id); // Auto-generated ID like "7f2ac1a4-..."
// Batch create for performance
await db.post({
type: 'analytics',
event: 'page_view'
}, { batch: 'ok' });Retrieves a document by its ID.
/**
* Retrieve a document by ID
* @param docId - Document identifier
* @param options - Optional retrieval parameters
* @param callback - Optional callback function (err, doc) => void
* @returns Promise resolving to document object
*/
db.get(docId, options, callback);Usage Examples:
// Basic document retrieval
const doc = await db.get('user_001');
console.log(doc.name, doc.email);
// Get specific revision
const oldDoc = await db.get('user_001', {
rev: '1-abc123def456'
});
// Get with revision history
const docWithRevs = await db.get('user_001', {
revs: true,
revs_info: true
});
// Get with attachment metadata
const docWithAttachments = await db.get('user_001', {
attachments: true
});Deletes a document from the database.
/**
* Delete a document
* @param docOrId - Document object (with _id and _rev) or document ID string
* @param optsOrRev - Options object or revision string
* @param opts - Additional options when second parameter is revision string
* @param callback - Optional callback function (err, response) => void
* @returns Promise resolving to DocumentResponse
*/
db.remove(docOrId, optsOrRev, opts, callback);Usage Examples:
// Delete using document object
const doc = await db.get('user_001');
const response = await db.remove(doc);
// Delete using ID and revision
const response = await db.remove('user_001', '2-def456ghi789');
// Delete with options
await db.remove('user_001', '2-def456ghi789', { batch: 'ok' });
// Alternative syntax with options object
await db.remove({
_id: 'user_001',
_rev: '2-def456ghi789'
});Retrieves information about the database.
/**
* Get database information
* @param callback - Optional callback function (err, info) => void
* @returns Promise resolving to database info object
*/
db.info(callback);Usage Examples:
const info = await db.info();
console.log(info);
// Output example:
// {
// "db_name": "my-database",
// "doc_count": 42,
// "update_seq": 123,
// "adapter": "idb",
// "auto_compaction": false
// }Permanently deletes the entire database.
/**
* Delete the entire database
* @param options - Optional destruction parameters
* @param callback - Optional callback function (err, response) => void
* @returns Promise resolving to operation result
*/
db.destroy(options, callback);Usage Examples:
// Destroy database
await db.destroy();
console.log('Database destroyed');
// Destroy with callback
db.destroy((err, response) => {
if (err) {
console.error('Failed to destroy database:', err);
} else {
console.log('Database destroyed successfully');
}
});Closes the database connection.
/**
* Close the database connection
* @param callback - Optional callback function (err) => void
* @returns Promise resolving when database is closed
*/
db.close(callback);Usage Examples:
// Close database
await db.close();
console.log('Database closed');
// Close with callback
db.close((err) => {
if (err) {
console.error('Error closing database:', err);
} else {
console.log('Database closed successfully');
}
});Compacts the database to reduce storage space.
/**
* Compact the database to reduce storage space
* @param options - Optional compaction parameters
* @param callback - Optional callback function (err, response) => void
* @returns Promise resolving to compaction result
*/
db.compact(options, callback);Usage Examples:
// Basic compaction
await db.compact();
console.log('Database compacted');
// Compact with options
await db.compact({
interval: 300 // Compact every 300ms
});interface DocumentResponse {
/** Indicates operation success */
ok: boolean;
/** Document ID */
id: string;
/** New revision identifier */
rev: string;
}interface DatabaseInfo {
/** Database name */
db_name: string;
/** Number of documents in database */
doc_count: number;
/** Current update sequence number */
update_seq: number | string;
/** Database adapter being used */
adapter: string;
/** Whether auto-compaction is enabled */
auto_compaction: boolean;
/** Additional adapter-specific information */
[key: string]: any;
}interface PouchDBOptions {
/** Specific adapter to use ('idb', 'leveldb', 'http', 'memory', etc.) */
adapter?: string;
/** Enable automatic compaction */
auto_compaction?: boolean;
/** Prefix for database names */
prefix?: string;
/** Database name (alternative to first parameter) */
name?: string;
/** Authentication credentials for remote databases */
auth?: {
username: string;
password: string;
};
/** Custom HTTP headers for remote databases */
headers?: { [key: string]: string };
/** Request timeout for remote databases (milliseconds) */
timeout?: number;
/** Skip setup of the database */
skip_setup?: boolean;
/** Additional adapter-specific options */
[key: string]: any;
}interface GetOptions {
/** Specific revision to retrieve */
rev?: string;
/** Include revision history */
revs?: boolean;
/** Include detailed revision information */
revs_info?: boolean;
/** Open specific revisions */
open_revs?: string[] | 'all';
/** Include attachment data */
attachments?: boolean;
/** Return attachments as binary */
binary?: boolean;
/** Include conflicts array */
conflicts?: boolean;
/** Additional retrieval options */
[key: string]: any;
}interface PutOptions {
/** Force new document creation (don't update existing) */
new_edits?: boolean;
/** Batch mode for better performance */
batch?: 'ok';
/** Additional creation options */
[key: string]: any;
}interface PouchDBError {
/** HTTP-style status code */
status: number;
/** Error name/type */
name: string;
/** Human-readable error message */
message: string;
/** Indicates this is a PouchDB error */
error: boolean;
/** Additional error details */
reason?: string;
}try {
const doc = await db.get('nonexistent-doc');
} catch (err) {
if (err.status === 404) {
console.log('Document not found');
} else {
console.error('Unexpected error:', err);
}
}
// Handle conflicts during updates
try {
await db.put({
_id: 'user_001',
_rev: 'old-revision',
name: 'Updated Name'
});
} catch (err) {
if (err.status === 409) {
console.log('Conflict - document was updated by someone else');
// Fetch latest version and retry
const latestDoc = await db.get('user_001');
await db.put({
...latestDoc,
name: 'Updated Name'
});
}
}
// Handle network errors for remote databases
try {
const remoteDB = new PouchDB('https://example.com/db');
await remoteDB.info();
} catch (err) {
if (err.status === 401) {
console.error('Authentication required');
} else if (err.status === 0) {
console.error('Network error - server unreachable');
} else {
console.error('Database error:', err.message);
}
}// Safe document update with conflict resolution
async function safeUpdate(db, docId, updateFn) {
try {
const doc = await db.get(docId);
const updatedDoc = updateFn(doc);
return await db.put(updatedDoc);
} catch (err) {
if (err.status === 409) {
// Conflict - retry with latest version
return safeUpdate(db, docId, updateFn);
}
throw err;
}
}
// Usage
await safeUpdate(db, 'user_001', (doc) => ({
...doc,
lastLogin: new Date().toISOString()
}));// Process multiple documents with individual error handling
const documents = [
{ _id: 'doc1', data: 'value1' },
{ _id: 'doc2', data: 'value2' },
{ _id: 'doc3', data: 'value3' }
];
const results = await Promise.allSettled(
documents.map(doc => db.put(doc))
);
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Document ${documents[index]._id} saved:`, result.value);
} else {
console.error(`Document ${documents[index]._id} failed:`, result.reason);
}
});