CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-pouchdb

PouchDB is a pocket-sized database inspired by Apache CouchDB that runs in the browser and Node.js.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

document-operations.mddocs/

Document Operations

Complete CRUD (Create, Read, Update, Delete) operations for documents in PouchDB, including individual document operations and bulk operations for high-performance scenarios.

Capabilities

Document Creation and Updates

Creates new documents or updates existing documents using the PUT method with explicit document IDs.

/**
 * Create a new document or update an existing document
 * @param document - Document to create or update (must include _id)
 * @param options - Options for the put operation
 * @returns Promise resolving to put result
 */
db.put(document: Document, options?: PutOptions): Promise<PutResponse>;

interface Document {
  _id: string;                           // Document ID (required)
  _rev?: string;                         // Revision ID (for updates)
  _attachments?: { [name: string]: Attachment }; // Binary attachments
  _deleted?: boolean;                    // Deletion marker
  [key: string]: any;                   // User-defined fields
}

interface PutOptions {
  force?: boolean;  // Force write without conflict detection
}

interface PutResponse {
  ok: boolean;      // Whether operation succeeded
  id: string;       // Document ID
  rev: string;      // New revision ID
}

Usage Examples:

// Create a new document
const doc = {
  _id: 'user123',
  name: 'Alice Smith',
  email: 'alice@example.com',
  created: new Date().toISOString()
};

const response = await db.put(doc);
console.log('Document created:', response.id, response.rev);

// Update an existing document
const existingDoc = await db.get('user123');
existingDoc.email = 'alice.smith@example.com';
existingDoc.updated = new Date().toISOString();

const updateResponse = await db.put(existingDoc);
console.log('Document updated:', updateResponse.rev);

Document Creation with Auto-Generated IDs

Creates new documents with automatically generated IDs using the POST method.

/**
 * Create a new document with auto-generated ID
 * @param document - Document to create (no _id required)
 * @param options - Options for the post operation
 * @returns Promise resolving to post result
 */
db.post(document: Omit<Document, '_id'>, options?: PostOptions): Promise<PostResponse>;

interface PostOptions {
  [key: string]: any; // Additional options
}

interface PostResponse {
  ok: boolean;      // Whether operation succeeded
  id: string;       // Auto-generated document ID
  rev: string;      // New revision ID
}

Usage Examples:

// Create document with auto-generated ID
const newDoc = {
  type: 'note',
  title: 'Meeting Notes',
  content: 'Discussed project timeline and deliverables',
  created: new Date().toISOString()
};

const response = await db.post(newDoc);
console.log('Document created with ID:', response.id);

Document Retrieval

Retrieves documents by ID with various options for including metadata, attachments, and revision information.

/**
 * Retrieve a document by ID
 * @param docId - Document ID to retrieve
 * @param options - Options for document retrieval
 * @returns Promise resolving to the document
 */
db.get(docId: string, options?: GetOptions): Promise<Document>;

interface GetOptions {
  rev?: string;         // Retrieve specific revision
  revs?: boolean;       // Include revision history
  revs_info?: boolean;  // Include revision info with status
  conflicts?: boolean;  // Include conflicting revisions
  attachments?: boolean; // Include attachment data
  binary?: boolean;     // Get attachments as binary instead of base64
}

Usage Examples:

// Get a document by ID
const doc = await db.get('user123');
console.log('User name:', doc.name);

// Get specific revision
const oldVersion = await db.get('user123', { rev: '2-abc123' });

// Get document with revision history
const docWithHistory = await db.get('user123', { 
  revs: true,
  revs_info: true 
});
console.log('Revision history:', docWithHistory._revisions);

// Get document with attachments
const docWithAttachments = await db.get('user123', { 
  attachments: true 
});

Document Deletion

Removes documents from the database. Documents are not physically deleted but marked as deleted.

/**
 * Delete a document
 * @param document - Document to delete or document ID
 * @param options - Options for the remove operation
 * @returns Promise resolving to remove result
 */
db.remove(document: Document | string, options?: RemoveOptions): Promise<RemoveResponse>;

interface RemoveOptions {
  [key: string]: any; // Additional options
}

interface RemoveResponse {
  ok: boolean;      // Whether operation succeeded
  id: string;       // Document ID
  rev: string;      // New revision ID (deletion marker)
}

Usage Examples:

// Delete using document object
const doc = await db.get('user123');
const response = await db.remove(doc);
console.log('Document deleted:', response.id);

// Delete using document ID and revision
const response = await db.remove('user123', '3-def456');

// Alternative syntax with document object
await db.remove({
  _id: 'user123',
  _rev: '3-def456'
});

Bulk Document Operations

Performs multiple document operations in a single request for improved performance.

/**
 * Perform bulk document operations (create, update, delete)
 * @param documents - Array of documents to process
 * @param options - Options for bulk operations
 * @returns Promise resolving to array of bulk results
 */
db.bulkDocs(documents: Document[], options?: BulkDocsOptions): Promise<BulkResponse[]>;

interface BulkDocsOptions {
  new_edits?: boolean;  // Whether to generate new revision IDs
  [key: string]: any;   // Additional options
}

interface BulkResponse {
  ok?: boolean;         // Whether operation succeeded
  id: string;           // Document ID
  rev?: string;         // New revision ID (if successful)
  error?: string;       // Error type (if failed)
  reason?: string;      // Error reason (if failed)
}

Usage Examples:

// Bulk create/update documents
const docs = [
  { _id: 'user1', name: 'Alice', type: 'user' },
  { _id: 'user2', name: 'Bob', type: 'user' },
  { _id: 'user3', name: 'Charlie', type: 'user' }
];

const results = await db.bulkDocs(docs);
results.forEach(result => {
  if (result.ok) {
    console.log(`Document ${result.id} saved with rev ${result.rev}`);
  } else {
    console.error(`Failed to save ${result.id}: ${result.error}`);
  }
});

// Bulk delete documents (set _deleted: true)
const existingDocs = await Promise.all([
  db.get('user1'),
  db.get('user2')
]);

const docsToDelete = existingDocs.map(doc => ({
  ...doc,
  _deleted: true
}));

await db.bulkDocs(docsToDelete);

Retrieve All Documents

Retrieves multiple documents with options for pagination, filtering, and including document content.

/**
 * Retrieve all documents in the database
 * @param options - Options for document retrieval
 * @returns Promise resolving to all documents result
 */
db.allDocs(options?: AllDocsOptions): Promise<AllDocsResponse>;

interface AllDocsOptions {
  include_docs?: boolean;    // Include full document content
  startkey?: string;         // Start key for range queries
  endkey?: string;           // End key for range queries
  limit?: number;            // Maximum number of documents
  skip?: number;             // Number of documents to skip
  descending?: boolean;      // Reverse sort order
  keys?: string[];           // Specific document IDs to retrieve
}

interface AllDocsResponse {
  total_rows: number;        // Total number of documents
  offset: number;            // Starting offset
  rows: AllDocsRow[];        // Array of document rows
}

interface AllDocsRow {
  id: string;                // Document ID
  key: string;               // Sort key (same as ID)
  value: { rev: string };    // Document metadata
  doc?: Document;            // Full document (if include_docs: true)
}

Usage Examples:

// Get all documents with content
const result = await db.allDocs({ include_docs: true });
result.rows.forEach(row => {
  console.log(`${row.id}: ${row.doc.name}`);
});

// Paginated retrieval
const page1 = await db.allDocs({ 
  limit: 10, 
  include_docs: true 
});

const page2 = await db.allDocs({ 
  limit: 10, 
  skip: 10, 
  include_docs: true 
});

// Range query
const userDocs = await db.allDocs({
  startkey: 'user_',
  endkey: 'user_\ufff0',
  include_docs: true
});

// Get specific documents
const specificDocs = await db.allDocs({
  keys: ['user1', 'user2', 'user3'],
  include_docs: true
});

Document Purging

Permanently removes document revisions from the database (advanced operation).

/**
 * Permanently purge a document revision
 * @param docId - Document ID to purge
 * @param rev - Revision ID to purge
 * @returns Promise resolving when purge is complete
 */
db.purge(docId: string, rev: string): Promise<void>;

Usage Examples:

// Purge a specific document revision
await db.purge('user123', '1-abc123');
console.log('Document revision purged permanently');

Error Handling

Document operations can fail for various reasons. Handle errors appropriately:

try {
  const doc = await db.get('nonexistent');
} catch (error) {
  if (error.status === 404) {
    console.log('Document not found');
  } else if (error.status === 409) {
    console.log('Document update conflict');
  } else {
    console.log('Unexpected error:', error.message);
  }
}

Common error codes:

  • 404 - Document not found
  • 409 - Document update conflict
  • 400 - Bad request (invalid document)
  • 401 - Authentication required
  • 403 - Permission denied

Install with Tessl CLI

npx tessl i tessl/npm-pouchdb

docs

changes-monitoring.md

database-management.md

document-operations.md

index.md

plugins-adapters.md

replication-sync.md

tile.json