Updating Fields Across All MongoDB Documents Using JavaScript

I'm currently facing an issue while updating a field for every Document within a MongoDB collection.

After successfully adding the field from the Mongo shell, I am looking to change the value of each field to a random number.

User.find({}, function(err, items){
  if (err){
    console.log('err');
    console.log(err);
  }
  items.forEach(function(item){
    var time = (Math.floor(Math.random() * (1474893715201 - 1474800000000) + 1474800000000));
    item.update({}, {$set:{"lastLogin": time}}, false, true);
  });
});

Upon logging each individual 'item' using console.log(item) within the .forEach loop, it retrieves every document in the collection as expected, indicating that everything is functioning smoothly up until this point.

Could anyone identify where I might be making a mistake?

Thank you!

Answer №1

To handle asynchronous Api calls, it is necessary to wrap the operation in a promise or use an async library to manage and execute the build changes effectively.

Another approach is to perform a bulk find and update operation in MongoDB using a single call: https://docs.mongodb.com/manual/reference/method/Bulk.find.update/

var bulk = db.items.initializeUnorderedBulkOp();
bulk.find( { status: "D" } ).update( { $set: { status: "I", points: "0" } } );
bulk.find( { item: null } ).update( { $set: { item: "TBD" } } );
bulk.execute();

Answer №2

How about trying something along these lines?

User.fetchAll({}, function(error, data){
  if (error){
    console.log('Error occurred');
    console.log(error);
  }
  data.forEach(function(element){
    var timestamp = (Math.floor(Math.random() * (4765710292013 - 4765700000000) + 4765700000000));
    element.lastVisit = timestamp;
    User.store(element); // or element.save() depending on the database driver
  });
});

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

Having trouble linking npm with webpack? Receive an error message saying "module not

I've been having trouble npm linking a module to a project that uses webpack as its bundler. Despite trying various solutions, I keep encountering the following error: ERROR in ./src/components/store/TableView.jsx Module not found: Error: Cannot reso ...

The D3 bar graph is displaying a height value of "Not a Number"

I'm working on incorporating a simple animated bar-chart into my webpage using the D3 (v7) library. This is part of a Django project, so the data for the chart is coming from my views.py file. However, when I try to display the chart, only part of it ...

Ensuring form accuracy upon submission in AngularJS 1.5: Understanding the $invalid state in relation to $pristine field

When loading data in a form, I want to allow the user to submit data only if the form is valid. Initially, the form is pristine but invalid. If the user edits any one of the three fields, the form is no longer pristine, which is acceptable. However, the ...

Problem Encountered with Jquery Validation for Name Field (Restriction to Alphabetic

I am struggling to validate a name format using a predefined jQuery validation tool. My intention is for the name field to accept only characters, but even with the correct regex pattern, it still allows numbers to be entered. The specific script I am us ...

Organize table information using rowspan functionality

View of Current Table I am looking to implement a side column in my table using rowspan to group dates within each pay period. The goal is for a supervisor to be able to create a new pay period, which will assign a unique integer in the database and then ...

How can you apply a class to a different element by hovering over one element?

Is there a way to darken the rest of the page when a user hovers over the menu bar on my website? I've been playing around with jQuery but can't seem to get it right. Any suggestions? I'm looking to add a class '.darken' to #conte ...

Deploying a pair of GitHub repositories to a unified Azure web application

Although this isn't exactly a technical question, I couldn't find a more appropriate stackexchange site for it. Recently, I made the move to Azure for deploying my backend web applications and APIs. I discovered that it's possible to deploy ...

problems with using array.concat()

I am attempting to reverse a stream of data using a recursive call to concatenate a return array. The instructions for this problem are as follows: The incoming data needs to be reversed in segments that are 8 bits long. This means that the order of thes ...

.toggleClass malfunctioning inexplicably

I've been struggling to make a div box expand when clicked and revert to its original size when clicked again. It seems like a simple task, but no matter what I try, I can't seem to get it right. I'm not sure where I'm going wrong, as t ...

Connecting MongoDB with Docker Compose

I am faced with a NodeJS server that needs to establish a connection with MongoDB. The entire setup is enclosed within docker compose, which includes NGINX as well. docker-compose.yml version: "3.5" services: api01: &api image: locali ...

Tips on incorporating svgo into a vite react project

One of the great features I've found in create-react-app is the ability to use SVGs as React components: import { ReactComponent as NotFound } from '@/assets/images/not-found.svg' function Error() { return ( <div> <NotF ...

Tips for retaining the selected radio button in a Java web application even after a page refresh

As someone new to web development using the Stripes Framework, I am encountering an issue with radio buttons on a webpage. When one of the radio buttons is selected, a text box and Submit Button appear. After clicking the Submit button, the functionality ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

Trigger video to play or pause with every click event

Looking to dynamically change the HTML5 video tag with each click of an li tag. Here is the current structure: <div class="flexslider"> <ul class="slides"> <li> <video> <source type="video/mp4" src="http://t ...

Creating labels dynamically with jQuery and HTML, then retrieving their text values through jQuery

During runtime, I am dynamically generating a label using jQuery with the following code: var value="Hello"; $("#ID_listOfTopics").append('<label id="ID_item">' + value + '</label><br /><hr />'); However, I&apo ...

What is the best way to condense this code into just a single line?

Being a beginner in javascript, node.js, and express, my main query revolves around streamlining the code below into a single line within the function. exports.about = function(req, res){ var mytime = new Date(); res.render('about', {title: &a ...

Having difficulty refreshing the JGrid with updated content

I am currently utilizing JQuery and JGrid in conjunction with Java. I have a grid set up <script> jQuery("#table1").jqGrid({ .............. ............ }); Additionally, I have another grid function abc { va ...

Error in mongoDB: Attempting to add duplicate data

I've been encountering an issue while attempting to insert data into a mongoDB document - I keep receiving a duplicate error message. https://i.sstatic.net/VvmmL.png Even though "role" is set as default:"customer" in the schema, adding data with a d ...

Guide for converting the initial letter of a key to lowercase in an object

Is there a way to change the first letter of a key in a JavaScript object to lowercase? For instance, if the key is Title, can it be transformed into title; or if the key is PublishDate, can it become publishDate? The complexity of the object may vary bas ...

Encountering surprising results while verifying a session token with parse.com

I am currently working on a project that involves using parse.com as my user manager. My goal is to create a login call to parse.com from the client side and then send the user's session token to my node.js server (which I will store as a cookie). On ...