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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With