Tips for performing a custom atomic update on a mongodb document

While MongoDB does offer the ability to perform atomic updates using findOneAndUpdate, it is limited to basic operations such as set or increment.

What I really need is a way to apply a custom function to transform my document:

const updateDoc = async (event) => {
  const oldState = await db.collection(collectionName).findOne({ name });
  const newState = customFunction(oldState, event);
  await db.collection(collectionName).replaceOne({ name }, newState);
}

This function will be invoked by a system that does not wait for promises to resolve before continuing operation, resulting in potentially multiple synchronous calls.

Is there a method to modify updateDoc to ensure atomicity so that when we execute:

updateDoc(event1); // without using await
updateDoc(event2);

We can guarantee that the stored document will reflect

customFunction(customFunction(initState, event1), event2)
?

Thank you

Answer №1

One effective way to handle this scenario is by implementing a task scheduler that queues and executes updates sequentially:

class TaskScheduler {
  constructor(){
    this.isRunning = false;
    this.taskQueue = [];
  }

  add(task){
     this.taskQueue.push(task);
     if(!this.isRunning) this.executeTasks();
  }

  async executeTasks(){
    this.isRunning = true;
    while(this.taskQueue.length) await this.taskQueue.shift()();
    this.isRunning = false;
 }
}

You can use it as follows:

 const jobScheduler = new TaskScheduler();

 const updateDocument = async (event) => jobScheduler.add( _ => {
   const previousState = await db.collection(collectionName).findOne({ name });
   const newState = processNewState(previousState, event);
   await db.collection(collectionName).replaceOne({ name }, newState);
});

updateDocument(event1);
updateDocument(event2);

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

Tips for updating sections of an array document

In my person document, there is a list of pets: { "personId": "kjadfh97r0", "pets": [ { "petId": "dfjkh32476", "name": "kitty", "kind": "cat" }, { "petId": "askdjfh2794857", "name": "rexy", "kind": "dog" ...

finding the source file or code where a particular html element is being generated

In the HTML file I have, there are multiple JavaScript files added. Whenever I run the HTML file, a title tag is automatically created in my HTML file. I do not want this title tag to appear in my HTML file. How can I prevent this from happening? Or how c ...

I encountered an issue in reactjs where I received the error message: TypeError: this.state.coords.map is not functioning properly

Here is the code snippet I wrote: import React, { Component } from 'react'; class LocationApp extends Component { constructor(props){ super(props) this.state = { coords:[], error:[], } } ...

Adding ngModel in the template causes the Angular component to load multiple times

I have been working on creating an Angular form and have successfully referenced the form in the Angular module. However, I am facing a problem where adding ngModel to an input textbox causes the Angular component to load multiple times on the page. Belo ...

Identifying a new browser tab in .NET: Tips and tricks

I'm trying to determine if a user has opened the homepage of my website in the same tab or in a new tab. Is there a way to check for this? ...

Restrict the length of mongoose schema

Is there a way to restrict the length of a mongoose schema, delete the oldest item when it reaches its limit, and add a new value to the schema? const mongoose = require("mongoose"); const Post = new mongoose.Schema({ User: { type: mongoose.Schema.Type ...

Utilizing jQuery boilerplate to execute functions

I am currently utilizing jQuery Boilerplate from However, I have encountered an issue where I am unable to call the "openOverlay" function within the "clickEvents" function. Oddly enough, I am able to successfully call "openOverlay" within the "init" fun ...

Utilizing the $.ajax method to navigate to a webpage displaying only the results that correspond to the value in the json data

I'm in the process of creating a single page application that utilizes $.ajax. Here is the JSON data: { "restaurants": [ { "id": 1, "name": "Denny's", "location": "Los Angeles", "cuisine": "American", "image_ ...

Creating Functional Tabs Using CSS and JavaScript

I've been experimenting with this code snippet, trying to get it to work better. It's still a work in progress as I'm new to this and have only customized it for my phone so far. The issue can be seen by clicking on the Projects and Today ta ...

What is the best approach to convert text to uppercase or lowercase based on the length of the string in Angular version 1.5?

My goal is to apply text formatting to a string named 'name'. Once the string is entered into an HTML form and the save button is clicked, the new formatted string should be displayed below the form. The formatting rule states that if the length ...

Optimizing jQuery Dialog for Different Window Sizes

I am currently developing a responsive website and facing a challenge. I need to implement a popup for window sizes smaller than 480px, but on desktop screens, the content should be visible without being inside the popup. I want to avoid duplicating the co ...

What is the best way to extract elements from an array object and store them in a separate array using JavaScript

Is there a way to extract specific values from an array object and store them in individual variables as arrays? // Given array const dummy = [ { id: 1, name: 'John', }, { id: 2, name: 'Jane', }, { id: 3, ...

The jQuery UI function .autocomplete() helps to enable autocomplete functionality

Autocomplete feature is successfully implemented on my website using the code below: $(function () { $("#client").autocomplete({ source: "/appointments/clients.json", minLength: 1, select: function (event, ui) { $(& ...

Generate a mongoose output by iterating through a loop within Koa.js

My current setup involves using Koa.js in combination with Mongoose.js. Within my MongoDB database, there exists a collection called css which has the following schema: _id css_name css_value In my code, I have an array that contains a large number of el ...

The node application route appears to be malfunctioning

Recently delving into the world of node JS, I encountered an issue while working on my application with the following 3 files. http.createServer(app).listen(**app.get('port')**, function(){ The error message reads 'undefined is not a func ...

React Select Event Bug: Not firing on subsequent attempts

My select filter menu has 5 different options that work fine when the page loads or refreshes. However, when I try to continuously select an option, it does not filter the content as expected. Here is a snippet of the code: <div className="filter_ ...

What is the best way to send a variable using $.post in a JavaScript script?

My jQuery and Javascript code below is responsible for handling the ajax request: else { $.post("http://www.example.com", {email: val}, function(response){ finishAjax('email', response); }); } joi ...

Please consider opening in a new tab rather than a new window

<a href='#' onclick="loadpage();">[RANDOM PAGE]</a> Whenever this code is clicked, the following function gets executed. function loadpage(){ $.ajax ({ type: "POST", url: "fetchpage.php", data: "showpage=1", success: function(msg) { ...

Encountering an Issue while Deploying a create-react-app to Heroku

Despite trying various online remedies, I am still encountering an error while attempting to deploy a simple React.js app on Heroku. The app successfully builds when I execute git push heroku master, but upon opening it, I consistently receive an applicati ...

Steps for choosing all choices in a multi-select menu without changing the order

What is the best way to choose all the options from a multiselect box using Java Script? ...