Using the native nodejs driver, how to simultaneously update a MongoDB document from two separate clients

I manage a group of individuals that require regular updates from various APIs, each with its own unique rate limits.

To handle this, I have multiple cron jobs set up with a similar structure:

const cursor_i = db.collection('users').find();

while(await cursor_i.hasNext()){

    let user = await cursor_i.next();

    user.field_1 = 'New Information';

    const write_result = await db.collection('newusers').save(user);
    if(!write_result.result.ok){
        console.log(write_result);
    }
}

However, a problem arises when multiple updaters are modifying the same document simultaneously, as only the last save() call takes effect.

Consider the following scenario:

const cursor_1 = db.collection('users').find();
const cursor_2 = db.collection('users').find();

let user_cursor_1 = await cursor_1.next();
let user_cursor_2 = await cursor_2.next();

user_cursor_1.new_field_1 = 'ok';
const write_result = await db.collection('users').save(user_cursor_1);
if(!write_result.result.ok){
    console.log(write_result);
}

// The first user now has a new_field_1 with the value 'ok'

user_cursor_2.new_field_2 = 'ok';
const write_result_2 = await db.collection('newusers').save(user_cursor_2);
if(!write_result_2.result.ok){
    console.log(write_result);
}

// The first user now has a new_field_2 with the value 'ok', but new_field_1 is no longer present

As a result, despite receiving two updates, the first user only retains the changes from the second update.

I could implement my own locking mechanisms, but I suspect MongoDB has built-in solutions for handling these situations.

Answer №1

After updating the initial cursor, it's essential to locate users by following this method:

const cursor_1 = db.collection("users").find();
let user_cursor_1 = await cursor_1.next(); // user_cursor_1 contains the first user in the collection

user_cursor_1.new_field_1 = "ok";
const write_result = await db.collection("users").save(user_cursor_1);
if (!write_result.result.ok) {
  console.log(write_result);
}

const cursor_2 = db.collection("users").find();
let user_cursor_2 = await cursor_2.next(); // user_cursor_2 includes the first user in the collection

user_cursor_2.new_field_2 = "ok";
const write_result_2 = await db.collection("newusers").save(user_cursor_2);
if (!write_result_2.result.ok) {
  console.log(write_result);
}

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

Internet Explorer automatically moves the cursor to the beginning of a textarea when it gains

When trying to insert "- " into an empty textarea, I am facing issues with Internet Explorer. While Firefox and Chrome work perfectly fine by inserting the text as expected, IE causes it to jump to the beginning of the textarea after insertion. Therefore, ...

Tips for identifying whether a form contains any empty fields and, if it does, directing focus to an anchor element

Is it possible to determine if a specific form contains any input fields? What about if it doesn't have any input fields? Additional Query: Also, how can I ensure that the focus is returned to a button when the page loads if the specified condition ...

Text that is curving around a D3.js pie chart

I am currently working on creating a 3D-Js chart and I would like the pie text to wrap around the pie itself. This is the exact effect that I am trying to achieve: https://i.sstatic.net/YOLdo.png I am facing two main issues: I am currently printi ...

Storing a chosen avatar in a database: A step-by-step guide

I am looking to display a selection of 10 avatars on my website for users to choose from. There will be no option for users to upload their own avatar. Users will simply click on the avatar image they want and then click the "done" button. The selected ava ...

What is the method for retrieving a variable from a Q Node promise?

I am currently developing a learning game utilizing Angular, Express, MongoDB, and Node. As part of my learning process, I have been exploring the use of promises to manage asynchronous operations effectively. One particular challenge I am facing involves ...

Is it possible for ng-change to invoke another controller?

Can someone help me with the following HTML code? <div ng-controller="select"> <select ng-options="n for n in names" ng-model="selected.item" ng-change="change()"> </select> </div> <div ng-co ...

JavaScript in IE/Edge may not run correctly if it is loaded from the cache

I am facing a peculiar problem with Internet Explorer (IE) and Edge. Upon initially loading a page, everything functions perfectly fine. However, if I navigate away from the page to another page on the same website, JavaScript errors start showing up on th ...

Video is not visible in safari browser initially, but becomes visible only after scrolling for a little while

Having issues with a video not displaying correctly in Safari? The problem is that the video only becomes visible after scrolling the browser window. Want to see an example of this issue in action? Click here and select the red bag. Check out the code sni ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

Searching across multiple attributes in Jquery UI Autocomplete: A comprehensive guide

My data is stored in an array of objects with a structure similar to this: $scope.usersList = [{ "name": "John", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f09a9f989eb088898ade939f9d">[email protected ...

Can you provide instructions on utilizing WYSIWYG for real-time label editing?

I am currently developing an online survey creator. The structure of a Question entity is as follows: [Question] int QuestionId { get; set; } int QuestionNumber { get; set; } String QuestionText { get; set; } QuestionType QuestionType { get; } When prese ...

What is the reason behind fullstack-angular generator utilizing Lo-Dash's merge rather than document.set?

This is the original code snippet used for updating: exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Thing.findById(req.params.id, function (err, thing) { if (err) { return handleError(res, err); } if(!thing) { ...

The use of `slot` attributes in Ionic has been deprecated and flagged by the eslint-plugin-vue

I encountered an error message while using VS Code: [vue/no-deprecated-slot-attribute] `slot` attributes are now considered deprecated. eslint-plugin-vue https://i.sstatic.net/DUMLN.png After installing two plugins in .eslintrc.js, I have the following c ...

Is it possible to retrieve a JSON response by making a jQuery.ajax request to an appengine URL?

Attempting to retrieve response data via ajax from the following URL: http://recipesid.appspot.com/api.user?method=user.query&[email protected] Encountering issues when trying to run the code. Please assist in resolving this problem. $.ajax({ ...

Invoking a function passed via props that utilizes react-router's features

I'm really struggling to grasp this problem. Is there anyone here who could help me out? I have a component where I pass a method called this.fetchContent as props named Filter. This method triggers an action creator that uses axios with Redux to fetc ...

What could be causing the malfunction in the cloning of the carousel item?

My goal was to create a carousel that displays multiple images in one slide. However, I encountered an issue where once the fourth image is reached, the other three images are forcibly hidden. I want to give credit to the original creator of this code snip ...

Utilizing Various Styles within a single Google Sheets Cell

In Cell A1, I have a challenge where I need to merge 4 different arrays of names, separated by commas. Each name should have its own styling based on the array it belongs to - red for array1, green for array2, orange for array3, and gray with a strike-th ...

Update app content without requiring users to download a new APK

Hey there, I'm new to all of this so I appreciate your patience. I'm working on a video based app and I'm wondering how I can add new videos/content to the app without having users download a new apk. I know I need to host the app on a data ...

SignalR blocking axios requests (In a Waiting State)

I am currently developing a project that involves bidding on products in Auctions with real-time updates of the bid price. With potentially thousands or even millions of users worldwide participating in the bidding process. We have implemented SignalR for ...

Problem: Vue 3 build does not generate service worker

After adding the "@vue/cli-plugin-pwa": "^4.5.12" to my package.json and setting up workbox configuration in my vue.config.js, I encountered an issue. When running npm run build:prd with the script vue-cli-service build --mode prod.exam ...