pouchdb / upsert

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

Add `updateIfExists` and/or `update` #55

Open Treora opened 7 years ago

Treora commented 7 years ago

I have the common scenario that I want to update a field in a document (e.g. when some async calculation completes), if that document still exists. upsert is almost suitable, except that it would recreate the document instead of ignoring or failing.

So I propose to create either (or both):

I'd be happy to provide a PR if you would agree on adding such an extra function (tell me which would be preferred).

chorpler commented 6 years ago

Can you just check in the upsert diffFunc to see if the document exists? If I'm understanding you correctly, that's what I do. Something like (I'm using an ES6 arrow function here):

db.upsert(documentID, (doc) => {
  if(doc._id) {
    // Document exists, so do whatever you want here and return the document
  } else {
    // Document does not exist
    return false;
  }
}).then(/*whatever*/)
Treora commented 6 years ago

@chorpler: Thanks for the suggestion. That is a way to achieve the updateIfExists behaviour indeed. It could possibly even serve as its implementation. However, this code suggests it performs an upsert while actually it does not perform an upsert, and even needs 4 extra lines of code to prevent this upsert from doing an upsert (+ comments & perhaps extra code in your tests).

Since this appears to be a common pattern, my idea was that it may be worth giving it a name, to make it more readable, writable, and tested. Just like upsert and putIfNotExists themselves are sugar for commonly used patterns. Do any maintainers think this too?