Expanding the Data in a Meteor Cursor

Is there a way to loop through a cursor and insert a new field into every document? I tried the following code, but it doesn't seem to be working:

function addNewField() {
    var items = Items.find();
    items.forEach(function(item) {
        item.newField = true;
    });
    return items;
}

I need to make changes to the documents in Iron Router's data function before passing them to the template.

Answer №1

When it comes to your specific needs -

If you're looking to calculate a value for each item, purely for display purposes (such as fields for the template):

Items.find({ /* selector */ }, {
   transform: function(item){
      item.newField = true;
      return item;
    }
}); 

However, if your goal is to update every document with unique values in MongoDB using Meteor's APIs:

var items = Items.find({ /* selector */});
items.forEach(function(item){
   var someValue = computeSomeValue(item);
   Items.update({
     _id: item._id
   }, {
      $set: {
         newField: someValue
      }
   });
 });

Alternatively, if you simply want to update all matched items with the SAME value:

Items.update({ /* selector */}, {
  $set: {
    newField: true
    },
  },
  { 
    multi: true
  }
);

If you are performing this task on the client-side in Meteor, the success of the last two options will also hinge on utilizing the insecure package or establishing appropriate allow or deny rules on the Items collection.

Answer №2

When it is unnecessary to uphold the cursor abstraction and you can simply return an Array:

function retrieveNewElements() {
  return Items.find().map(function(item) {
    return _.extend(item, {newField: true});
  });
}

If you are adamant about maintaining a cursor abstraction, you could manage Items.find().observe callbacks that preserve newField on a local collection (for example,

NewItems = new Meteor.Collection(null)
) from which you would provide a cursor to a caller.

Answer №3

If you need to modify the items in your local MongoDB cache, make use of MongoDB update operators for efficient updating: Click here for more information

Answer №4

There are various methods to achieve your desired outcome, but if you opt for iterating over your cursor using forEach, it's crucial to understand that once a cursor is manually iterated within forEach, map, or fetch, it needs to be rewound according to the official documentation.

For a similar issue, refer to this answer.

function updateItems() {
    var items = Items.find();
    items.forEach(function(item) {
        item.updatedField = true;
    });

    items.rewind(); // Resetting the cursor position here

    return items;
}

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

Create a bookmarklet for Webdriver when initializing the driver, or store the bookmarklet in your saved bookmarks, all done without the need to

Need Help Adding Custom Bookmarklet to Webdriver I am looking for a way to include a custom bookmarklet (a bookmark that consists of pure JavaScript code) in a webdriver so it appears on the bookmarks toolbar. I would like to achieve this either during th ...

Template not being properly populated by handlebar for JSON output

Hello there! I am currently working on making an http GET call to an MVC controller action which returns JSON data. The JSON data looks something like this: [ { "PlanCode": "P001", "PlanName": "Plan1" }, { "PlanCode": " ...

Tips on transferring a value from one JavaScript file to another JavaScript file

Currently, I am able to pass parameters from one JavaScript file to another using the jQuery method "$.getScript". For example, in the "secondJavaScript.js" file, I use a $.getScript call to invoke the function callMemoPage() from "firstJavaScript.js", p ...

How can I specify the array's length when using JSON.stringify in AngularJS?

I am looking to store form values in JSON to send via $http.post. One of the values, rooms, should be an array with a length determined by the selected value from md-select. The value of Adult should be included within each room entry. var data = { rooms: ...

What is the reasoning behind the "open in a new tab" function triggering a GET request?

Check out this HTML tag: <a href="#" id="navBar_navBarInput_3_subNavDropdownInput_0_subNavLinkInput_0" onclick="redirectPost(4,'EntryData.aspx');">My Cool Link</a> The Javascript function "redirectPost" function redirectPost(id, ur ...

Updating the scope variable in an AngularJS directive

Recently delving into Angular, I encountered an issue: I have both a list view and a details view with tags. To facilitate navigating between the two views and loading new elements from a service upon click events, I created a directive. My aim is to also ...

Sending Javascript variable to AngularJS

I'm a beginner in the world of AngularJS and JavaScript, and I'm struggling to figure out how to pass a JavaScript variable into my AngularJS controller. Here's the snippet from my html page: <!DOCTYPE html> <html lan ...

The object's texture remains static and does not follow its rotation

My simple object has a texture drawn onto it using a shader. Everything is working correctly, except when I rotate the object, the texture does not rotate along with it. Instead, it seems to remain in a 2D space, creating the 'mask' effect shown ...

Incorporating angularjs within a page loaded with jquery.load

Currently, I am in the process of developing a web application designed to cater to multi-device applications. The foundation of this project involves a framework built using nodejs, socket.io, and express which manages the distribution of views. This fra ...

Ways to update the select field without having to reload the entire page

I am working on a unique feature that involves two levels of drop down menus. When a user makes a selection in the first level, a corresponding set of options will appear in the second level. For example, I have 6 options in the first level, each with its ...

Although JavaScript Handlebars does not show any errors, it fails to function properly

I've been attempting to update text on my page using handlebars, but unfortunately, it's not functioning correctly and there are no error messages being displayed. The code below is triggered once the user clicks the submit button <button ty ...

Manage text, PDF, and image files in a MEAN stack app by uploading and fetching them from a MongoDB database using

I have been working on developing a piece of code that allows users to create a dynamic URL, upload a file by clicking a button on the page, and then download the same file in the same format when revisiting the URL. The functionality is similar to cl1p, b ...

Sending data with an AJAX post request from JavaScript to a Python backend

Attempting to pass a dictionary from JavaScript to a Python script using AJAX POST method. Here's the JavaScript code: function foo(){ context = { 'var1': val1, 'var2': val2 } $.ajax({ ...

Is there a way to utilize flex or other CSS properties to wrap element content onto the next line, beginning from the start of its container?

Is there a way to wrap the text content of an element onto the next line, starting from the beginning of its container? I'm looking for something similar to the image provided. Can this be achieved using flexbox or other CSS properties? Here's a ...

The hover effect is functional on the majority of browsers, with the exception of Safari and Chrome on a Mac computer

Within my html code, there are various tiles containing two images (one in jpg format as the background and one in png with transparency as the foreground) along with a hover effect: When hovering over a tile, the image zooms in towards the position of the ...

Choose the DIV element based on its data attribute using JSON

When using each(), my goal is to: Hide all divs where the data-infos.grpid = $jQuery(this).data('infos').grpid Show the next div where data-infos.ordre = $jQuery(this).data('infos').next_ordre I am unsure how to apply a "where" ...

The send_keys() function in Selenium version 3.141.0 works perfectly on Windows, but unfortunately, it is not functioning correctly on Linux Debian 11

I've been experimenting with web automation using Selenium. Everything was running smoothly until I updated my packages - now the send_keys() method isn't functioning on Linux, but it's working fine on Windows with the same versions. I&apo ...

"Exploring the depths of sub directories in Node.js: A guide to printing

Once again, I find myself stuck with node.js and in need of your assistance. I am attempting to write a script for the command line interface that will search for all subdirectories under the current directory (process.cwd), and only print out those that ...

Retrieve items from a JSON file based on the user input ID in a React project

Hi there, I'm looking for guidance on how to extract items by name from a JSON file based on user input. The JSON file contains both an id and name for each item. My goal is for the user to enter a number, which will then display the corresponding ite ...

Pressing the up arrow in Javascript to retrieve the most recent inputs

Is there a way to retrieve the most recent inputs I entered in a specific order? For example: I have an array with 20 elements, and every time I enter something, I remove the first element from the array and add the new input at the end. So, when I press ...