Mongo: executing queries with both .find() and .update() methods sequentially

I am looking to:

  1. Retrieve specific items from collection X;
  2. Retrieve other items from X;
  3. Make the items from step #1 have the same value as the items from step #2
  4. Make the items from step #2 have the same value as the items from step #1

Essentially, I need to perform a swap.

However, my initial attempt resulted in updating all records to On instead of swapping the values.

The code I used:

var cursorOn = db.car.find({T: 'e46dba7', State: "On"});
var cursorOff = db.car.find({T: 'e46dba7', State: "Off"});

while (cursorOn.hasNext()) {
    doc = cursorOn.next();    
    db.car.update(
        {_id: doc._id},
        {$set:{"State": "Off"}},
        {writeConcern: { wtimeoutMS: 50000 }}
    );
}

while (cursorOff.hasNext()) {
    doc = cursorOff.next();    
    db.car.update(
        {_id: doc._id},
        {$set:{"State": "On"}},
        {writeConcern: { wtimeoutMS: 50000 }}
    );
}

I also attempted using async/await, but encountered a SyntaxError:

let cursorOn = await db.car.find({T: 'e46dba7', State: "On"});
let cursorOff = await db.car.find({T: 'e46dba7', State: "Off"});

The error message was:

SyntaxError: Unexpected identifier at /root/MongoScripts/update.js

How can I adjust the code to ensure a synchronous operation for the desired result? Thank you.

Answer №1

It seems like the issue you're facing is due to your cursorOn and cursorOff cursors interacting with a live resultset instead of separate snapshots.

Here's a breakdown of what might be happening:

  1. cursorOn is set to filter for { "State": "On" }.
  2. cursorOff is set to filter for { "State": "Off" }.
  3. cursorOn goes through all the "On" documents and changes them to "Off".
  4. cursorOff then goes through all the "Off" documents, including the ones changed to "Off" in Step #3.

As a result, all documents initially marked as "On" or "Off" end up being switched to "On", as you've noticed.

Instead of using a cursor, you may want to work with an eagerly-loaded array by using the toArray method on the cursor. Consider adding a projection to only retrieve the IDs of the relevant documents.

I'm not a MongoDB expert, but this is how the issue appears to me. I hope this explanation is helpful.

Answer №2

Although I'm not a jQuery deferred expert, I have used it effectively to synchronize logic processes

$.when(firstFuntion).then(secondFunction);
​
function firstFunction (cursorOn) {

    var $dfd = $.Deferred()

    while (cursorOn.hasNext()) {
        doc = cursorOn.next();    
        db.car.update(
            {_id: doc._id},
            {$set:{"State": "Off"}},
            {writeConcern: { wtimeoutMS: 50000 }}
        );
    }

    return $dfd.promise()
}

function secondFunction (cursorOff) {

    var $dfd = $.Deferred();

    while (cursorOff.hasNext()) {
        doc = cursorOff.next();    
        db.car.update(
            {_id: doc._id},
            {$set:{"State": "On"}},
            {writeConcern: { wtimeoutMS: 50000 }}
        );
    }

    return $dfd.promise();
};

By using the when-then method, you can effectively control the sequence of execution by utilizing promises - the .when() function will wait until the .then() function's promise is fulfilled.

Hopefully, this explanation aids you in your endeavors or sparks some innovative ideas :)

Edit: I almost forgot to provide a link to jQuery deferred.promise(); I trust it will be beneficial.

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

Align the date input field to the center for better visual appeal

I am facing a challenge in centering the date in an input, not the entire input element inside a div. When I attempt to center it, the date gets positioned within a portion of the input due to a resizable right-hand side panel for selecting a date from a c ...

Error receiving parameter in express route callback function

At the moment, I have been working with a number of routes in Express. Some routes are quite lengthy and tend to look like this: router.get('/api/comments', function(req, res, next){ Comment.find({"user": req.payload._id}).exec(function(err,co ...

"Error: The definition of the onclick function in jQuery is

I'm currently facing an issue with an ajax script in WordPress. I am attempting to post from a function using an onclick href, but it keeps showing up as undefined. I have tried rearranging the code both inside and outside of the scope, but I haven&ap ...

Execution of Node.js express with mongodb calls is not completing

I am facing an issue with a .post function that involves using a mongodb call. Here's a simplified version of the code: router.post('/insert')=>{ -findOne // Some code // if there's an error, return redirect('/error') -C ...

Error encountered: Unexpected token when defining inline style in React

When attempting to prevent scrolling on the page by using style='overflow-y: auto;': render() { return ( <div style={{overflow-y: auto}}> <div>{this.props.title}</div> <div>{this.props.children}& ...

Is it possible to calculate a variable within a dataset using existing data as a reference point?

Is there a way to dynamically compute some of the data variables in a Vue instance by referencing other variables and tracking their changes? new Vue({ el: '#root', data: { x: 1, y: x + 1 } }) <script src="https://cdnjs.cloudf ...

Adding individual names for elements in a list using Jackson

Is there a way to assign a unique name to each element in a JSON list using JACKSON? For instance, consider the following JSON data: {"result": [ { "name": "ABC", "age": "20" },{ "name": "DEF", "age": "12" } ]} Howeve ...

Retrieve the temporary file path using JavaScript/jQuery

Here is the code snippet: <div> <label class="control-label" for="Name">Add XML</label> </div> <div> <input id='upload' name="upload[]" type="file" accept=".xml"/> </div> <script src="//c ...

Ways to patiently wait in a for loop until the ajax call is completed

I am a beginner in web development and currently working on a small website project that involves using ajax to display new comments. Below is the function I have created: function show_comments() { $('div#P_all_posts>div').each(function () { ...

MongoDB querying based on conditions

I am a beginner when it comes to MongoDB and node.js, and I could really use some guidance on performing a mongo lookup. My goal is to join two documents based on a specific condition within my Conversation model using mongoose, node, and express. Let&apo ...

Shifting an element to the right before revealing or concealing it with Jquery Show/Hide

$(document).ready(function(){ var speed = 700; var pause = 3500; function removeFirstElement(){ $('ul#newsfeed li:first').hide('slide', {direction: "up"}, speed, function() {addLastElement(thi ...

Animating several elements by toggling their classes

I'm struggling to implement smooth animations on this box. I've tried using 'switchClass' but can't seem to keep everything together. Any help would be greatly appreciated. Here is the code snippet for reference: <script src=" ...

The updateOne stitch function encounters errors with the message "update not allowed."

I encountered an issue with my Stitch function that handles multiple tasks. The error appears to be stemming from this particular line of code: try { // voteAsObjectId is the Id of the photo to vote converted to BSON.ObjectId. await db .collection ...

Retrieving and assigning data values within an Angular JS service

Here is the service I created to fetch user details: angular.module('app') .factory('userDetailService', function($http) { var userData = {}; function getUserDetails(userId) { if (userId) { return $http.get ...

Protractor test freezes after attempting to click on an element

I have encountered a challenge while attempting to write a protractor test that selects an item from a custom dropdown menu. The issue arises when trying to click on an element other than the last one in the list, as it hangs and times out. Interestingly, ...

How can a MongoDB ObjectId be incorporated as an optional parameter in C# without the need for function overloading?

In C#, using an ObjectId as an optional argument can be challenging because ObjectId is a struct without a "Design time constant" default value. Trying to use ObjectId.Empty or default(ObjectId) will not work for the same reason. Is there a solution avai ...

Triggering the onClick event in React to invoke another class components

I'm currently working on implementing a modal popup (stored in the PostView class) so that it appears when any post in the postcontainer class is clicked. As I am new to React, I would greatly appreciate any suggestions for enhancing the code. Post C ...

What is the best way to extend the width of an element within a Bootstrap column beyond the column itself?

Apologies for any language errors, but I have a query regarding Bootstrap. I am currently working on making a website responsive and I have a row with 4 columns set up like this: The "seeMore" div is initially hidden and on clicking the boxToggle element ...

Unable to get OverlayView() from Google Maps API to function within an AngularJS directive

My directive "map" is encountering a namespace issue. The mapInit() function is working perfectly, but there seems to be an error with my OverlayView() object that I can't seem to resolve. This is the initial step outlined in the Google documentation ...

Setting up paths to bypass authentication on an Express website

Currently, I am in the process of developing an application using node and express. I have implemented a passport authorization middleware for all routes as part of my highly modular approach to building the app. One challenge I have encountered is when tr ...