Home > Back-end >  How to fetch one by one record from couch db
How to fetch one by one record from couch db

Time:03-11

Just assume, I'm having the 1000 records in my couch database. Need to fetch one-by-one records in nodeJS.

I'm trying to get the record but not able to fetch one by one

CodePudding user response:

The OP tags include both couchdb and couchbase which are not the same. I am assuming CouchDB for this answer and so couchdb-nano fits the bill.

The basic strategy is to get the first document from the /{db}/_all_docs endpoint by limiting the results to one document with the limit parameter, then leverage the start_key, limit and skip parameters to get the next document.

For example,

const nano = require("nano")("http://user:pass@localhost:5984/");
const dbName = "stack";

// Do the thing
(async () => {
    let processed = 0;
    let total_docs = 0;
    try {
        const db = await nano.db.use(dbName);
        let result = await db.list({ limit: 1 });

        total_docs = result.total_rows;

        while (result.rows.length) {
            if (processDocument(result.rows[0])) {
                processed  ;
            }
            result = await db.list({ start_key: result.rows[0].key, limit: 1, skip: 1 });
        }
    } catch (err) {
        console.error(err);
    }
    console.info(`\nProcessed ${processed} of ${total_docs} documents`);
})();

// Returns true of the document was processed, false if skipped.
function processDocument(doc) {
    if (doc.key.startsWith("_design/")) {
        return false;
    }
    console.log(doc.key);
    return true;
}

  • Related