Is there a safe way to Compare and Swap document values in MongoDB in a related collection with Local API, or do we have to use the collections model manually?
AFAICT, doing the operation directly on Mongoose model might be the only possible route.
I'm curious to learn more what you're trying to achieve
@456226577798135808. You're wanting to read and evaluate the current state of the document before updating? Could this be done with hooks?
I am looking into Palyoad-CMS and learning about the challenges I can meet in creating an advanced app or site. My concern is updating related stock or an array in other collections using hooks. If two customers, for example, are buying the same product, we need to update the product's stock or other related data simultaneously. A simple example is reading an array from a collection, adding your records, then saving the data; the other user's array then overwrites the other user's array.
For stock here's how I'd imagine the flow working: The user's order collection would have a relationship to the product which knows about its own stock. You'd then check the stock when adding to an order and also when executing the order during checkout. The order placement would then have a hook adjusting the stock count.
You could obviously make this much smarter and safer with more checks throughout the process. I'm not entirely clear on the scenario you're describing for arrays though.
That is a great workflow; thanks! What about atomicity and concurrency updating from hooks? If multiple checkouts are in a scaled environment. Suppose the stock of a product has an array of different variants of the product. User one reads the array of stock; user 2 reads the array of stock. User 1 updates the array; User 2 updates the array. Then user 2 overwrites user one's array. Can Payload do "update if current"?
There is nothing built-in currently to handle that specific scenario. We have db transactions on the roadmap which could help in this type of scenario. In lieu of that, doing a check before order execution and at other steps is the only solution I can think of.
Star
Discord
online
Get dedicated engineering support directly from the Payload team.