Atomic Update One Using Waterline JS
<h1>Goal</h1>
<p>I want to update a single record based on search criteria (similar to findOne, but I want to updateOne). This has to be atomic though because a <code>.find() then .update()</code> would take advantage of the <em>wonderful</em> asynchronous nature of node and leave the record open for alteration after find and before update.</p>
<h1>Example</h1>
<p>Let's say to simplify things that I have records of my possessions I want to loan to friends though a site. If two friends simultaneously wanted to borrow any book available, I would need to mark its attribute as in-use to prevent problems.</p>
<p>If I used <code>Book.find(available==true)</code> and then <code>Book.update(book, available=false)</code>, this could have a race condition where the thread runs <code>.find()</code> and while waiting to hear back from the DB, calls <code>.find()</code> for the other user, both resulting in the same book to loan. This is obviously a problem and is what I want to protect against.</p>
<h1>Question</h1>
<p>How do I protect against this scenario? Is there a way to update one record using the helper methods of waterline? Or do I need to conduct a native SQL query?</p>