Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Fields to a Meteor Cursor

How can I iterate over a cursor and add a field to each document? Something like this, which doesn't seem to work:

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

I want to modify the documents in Iron Router's data function before sending it to the template.

like image 205
jacksondc Avatar asked Jan 18 '26 23:01

jacksondc


2 Answers

Depending on your exact requirement -

if you want to compute a value on each item, just for display purposes (eg fields to use in the template):

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

But, if you would like to update every document with different values (in mongodb), using the Meteor api's:

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

otherwise, if you just want to update every matchhed item with the SAME value:

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

If you're doing this client-side in Meteor- your success (on the last two options) will also depend on using the insecure package or setting correct allow or deny rules on the Items collection.

like image 93
nathan-m Avatar answered Jan 20 '26 14:01

nathan-m


If you don't need to maintain the cursor abstraction and can just return an Array:

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

If you insist on maintaining a cursor abstraction, you could handle Items.find().observe callbacks that maintain newField on a local collection (e.g. NewItems = new Meteor.Collection(null)) from which you would yield a cursor to a caller.

like image 24
Donny Winston Avatar answered Jan 20 '26 13:01

Donny Winston