Open Treora opened 7 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*/)
@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?
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):
updateIfExists
, that would be likeupsert
but fail silently if the document does not exist. I think fits nicely as a dual toputIfNotExists
.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).