Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add updateIfExists and/or update #55

Open
Treora opened this issue Jul 26, 2017 · 2 comments
Open

Add updateIfExists and/or update #55

Treora opened this issue Jul 26, 2017 · 2 comments

Comments

@Treora
Copy link

Treora commented Jul 26, 2017

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):

  • a function updateIfExists, that would be like upsert but fail silently if the document does not exist. I think fits nicely as a dual to putIfNotExists.
  • a function update; same idea, but it would fail loudly instead of silently (perhaps better, since it gives the choice whether to ignore the failure).

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
Copy link

chorpler commented Aug 2, 2017

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
Copy link
Author

Treora commented Aug 3, 2017

@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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants