Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

MongoDB Compare and Swap with local api

default discord avatar
Deleted User3 years ago
6

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?

  • default discord avatar
    squareclamp3 years ago

    AFAICT, doing the operation directly on Mongoose model might be the only possible route.

  • discord user avatar
    denolfe
    3 years ago

    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?

  • default discord avatar
    Deleted User3 years ago

    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.

  • discord user avatar
    denolfe
    3 years ago

    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.

  • default discord avatar
    Deleted User3 years ago

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

  • discord user avatar
    denolfe
    3 years ago

    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 on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.