Implementing Pessimistic Locking in MongoDB for Collections

Hello, I am seeking your expertise and creative guidance on a project I have been struggling to solve. My goal is to enable users to manipulate a collection of orders in a stock market application. It is imperative that these orders are executed one by one, as each order corresponds to a single document in the stock's collection. Despite my efforts to implement manual locking methods, I am facing challenges with orders executing out of sequence.

var stringType = "locked";
var checkIt = await stocksLS.collection(data[5]).findOneAndUpdate({"editor": {$exists:false}},
{$set: {editor: [stringType]}},
{
sort:{"Price":1,"TS":1}
}
);

The code snippet above demonstrates my attempt to lock the next best order for execution, based on price and timestamp. However, simultaneous order executions by multiple users result in future orders being processed prematurely, disrupting the intended sequence.

My proposed solution involves applying locks to all documents during an order execution, and allowing incoming orders to repeatedly attempt to queue up until they can successfully secure a lock.

I acknowledge that there may be more efficient solutions to this issue, and I welcome any suggestions or ideas you may have to improve the process. Your input would be invaluable in helping me explore better alternatives. Thank you for your time and consideration.

Answer №1

If you're in need of a queue, don't reinvent the wheel. Opt for a pre-existing queue solution available in your preferred programming language (like JS).

While it's tempting to create your own queue from scratch, dealing with bugs that arise can be time-consuming. It's easier to rely on a well-tested and established queue library.

Keep in mind that MongoDB is not designed as a queue system and does not offer built-in queue functionality on the server side.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using I18Next fails to function properly while trying to retrieve data from the backend

After integrating i18next into my application and fetching data from the backend (i18next-xhr-backend), I encountered an issue. Although there were no errors, the translation was not functioning as expected. I am using Vue along with Webpack. Below is a s ...

Sending information to a PHP script using Ajax

I am working on a project that involves input fields sending data to a PHP page for processing, and then displaying the results without reloading the page. However, I have encountered an issue where no data seems to be passed through. Below is my current s ...

What is the best way to render images on the server side in React?

I've got this snippet of code residing in my server/server.js import path from 'path'; import fs from 'fs'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; import express from 'ex ...

I'm looking for the specific jQuery/JavaScript function that will accomplish this task

let data = [{ name: "abcd", type: "1 kg" }, { name: "efgh", type: "1 cai" }, { name: "ijkl", type: "1 kg" }]; If I have the name, I would like to get the corresponding type. For example, if I call getType('abcd'), it sho ...

Setting a fixed data value within a div for subsequent retrieval through a function

I found a helpful example that demonstrates how to convert numbers into words. You can check it out here. The function for converting numbers into words is implemented in the following HTML code: <input type="text" name="number" placeholder="Number OR ...

Ways to extract value from all chosen dropdown list elements

<table id="tb_Answers"> <tbody> <tr> <td> <select class="ddl_NextQuestion" name="_ctl0"> <option value="0">End</option> <option val ...

What steps should be taken to resolve the error message "TypeError: Cannot read properties of undefined (reading 'toLowerCase')?"

After creating a basic search bar, I encountered an issue when typing in it for the first time: TypeError: Cannot read properties of undefined (reading 'toLowerCase') However, when I closed the pop-up and tried again, the search bar worked prope ...

Revamping an npm package on GitHub

Currently, I am managing a project that has gained popularity among users and has received contributions from multiple individuals. The next step I want to take is to convert the entire library into TypeScript, but I am unsure of the best approach to ach ...

Error: The status code provided is not valid: undefined [Node.js and mongoDB]

When attempting to utilize a method that I have defined in my schema, an error occurs specifically when making a POST request. Below is the static method present in the Schema: usuarioSchema.static.checkIfUserExists = function(email, cb){ const query ...

What is the method for accessing the Redux store content directly in the console, without using any developer tools

By utilizing React Devtools, I am able to access the store by: $r.store.getState() Is there an alternate method to retrieve the store without using React Devtools? ...

Seamless camera shift as the mouse returns to the canvas - Three.js

My goal is to use Three.js to make an object follow the mouse movements of a user. Currently, when the mouse moves outside of the canvas and then back in at a different spot, the object abruptly jumps to the new mouse position. I am looking for a way to c ...

What is the best method for extracting an attribute value from an HTML <a> element?

I've been attempting to scrape the specified website, but I'm having trouble retrieving the value of the 'data-link' attribute. Is there anyone who can assist me with this issue? //first try (resulting in an error) const puppeteer = ...

Learn the ins and outs of utilizing *ngIf in index.html within Angular 8

Can anyone explain how I can implement the *ngIf condition in index.html for Angular2+? I need to dynamically load tags based on a condition using the *ngIf directive, and I'm trying to retrieve the value from local storage. Below is my code snippet b ...

Move a Bitnami-deployed EC2 instance containing a Nodejs+MongoDB app to a different AWS account

After initially deploying my Node.js + MongoDB application on an AWS EC2 instance, I now need to transfer it to a different AWS account. I found a helpful video tutorial that guided me through the process: https://aws.amazon.com/premiumsupport/knowledge-c ...

AngularJS requires that JSON object property values be converted to strings in order to be displayed as actual templates

Each tab click accesses a json array containing unique templates such as ui-grid or c3 chart directive (c3.js). When a specific tab is clicked, the template in string format must be rendered into actual templates like ui-grid, c3-chart, etc. var sampleJs ...

Tips for saving an image stored as a byte[] array in MongoDB to be used for the Do

Hey, I was wondering how to store a byte image in MongoDB and perform OCR processing through a public static void main method. Is it possible to perform OCR on a stored image from MongoDB? Model: public class Photo { @Id private String id; ...

Steps to deploy a create-react-app-2 build on an IIS server

Currently, I am attempting to deploy a React.js application that was developed with create-react-app (react-scripts v2.1.5) on an IIS server. Despite my best efforts, I continue to encounter frustrating type errors like the ones shown in this image: https ...

Retrieving the original state value after updating it with data from local storage

Incorporating the react-timer-hook package into my next.js project has allowed me to showcase a timer, as illustrated in the screenshot below: https://i.stack.imgur.com/ghkEZ.png The challenge now lies in persisting the elapsed time of this timer in loca ...

How to update a timestamp field using MongoDB and the Golang driver

I am currently utilizing the official MongoDb Driver for Golang. Within my Golang code, there is a field with a timestamp type that I need to update. Below is the struct I am working with (the lastUpdate field is the timestamp field): import ( "conte ...

Instructions on setting up a custom HTTPS server using the Alexa ask-cli

I am facing an issue with deploying my Alexa skill using the alexa-cli tool (https://www.npmjs.com/package/ask-cli). Whenever I try to deploy my skill with an https server, I encounter the following error: ◞ Creating new skill...Call create-skill err ...