pouchdb / upsert

PouchDB plugin for upsert() and putIfNotExists() functions
Apache License 2.0
149 stars 25 forks source link

question: bulk upserts example? #13

Closed angelxmoreno closed 8 years ago

angelxmoreno commented 8 years ago

Does it support bulk operations? Can I haz example?

nolanlawson commented 8 years ago

No, it doesn't. Sorry! Please use allDocs() and bulkDocs() instead if that's what you want.

schamp commented 8 years ago

I'm relatively new to pouchdb and node, and it's rather a nasty hack, but here's the first cut of how I did a bulk-upsert type thing, which seems to work. It only updates if there is some difference in the document, and it just blows the existing document away. If the documents are the same it does nothing (to avoid unnecessary revisions):

var unconditional_upsert = function(new_doc) {
    return db.upsert(new_doc._id, function(old_doc) {
        // remove the rev, so we can compare
        delete old_doc._rev;
        // plain old comparison won't catch matching arrays, etc.
        if (!_.isEqual(old_doc, new_doc)) {
            return new_doc;
        }
        return false;
    }).catch(function(err) {
        console.log("Error upserting: " + err);
        console.log("Old Doc: ");
        console.log(old_doc);
        console.log("New doc: ");
        console.log(new_doc);
    });
};

var bulk_upsert = function(docs) {
    var promises = docs.map(unconditional_upsert);
    return Q.all(promises);
};
nolanlawson commented 8 years ago

You can use .map instead of .forEach, but other than that, your code looks good. :)

schamp commented 8 years ago

Of course, thanks!