Reputation: 1246
I'm trying to use cursor.observe({added})
to calculate a new field based on the inserted fields. Using Docs.update()
with the added document breaks if observing on added
, Meteor seems to get stop in a loop before imploding. However, updating on changed
works.
Why? And how would I go about calculating the new field on insertion?
See comments:
Meteor.startup(function () {
var cursor = Docs.find();
var handle = cursor.observe({
added: function (doc) {
// This breaks Meteor. Meteor gets stuck in a loop and breaks.
Docs.update(
doc._id,
{$set: {metric: getCalculatedMetric( doc.x, doc.y )}}
);
// However, this would log once as expected.
// console.log(doc.name + ' has been added.');
},
changed: function (doc, oldDoc) {
// This works as expected, updates myField.
Docs.update(
doc._id,
{$set: {metric: getCalculatedMetric( doc.x, doc.y )}}
);
}
});
});
Upvotes: 0
Views: 570
Reputation: 2803
not sure why this would be a problem, but i have something very similiar working using methods
CollectionName.find({}).observe({
added: function(document){
Meteor.call('doSomething', {
id: document._id
});
},
changed: function(newDocument, oldDocument){
Meteor.call('doSomething', {
id: newDocument._id
});
}
});
if this works for you, if would have the added benefit of removing duplicate calculation code
my method does use a more granular query, but that shouldnt be an issue
doSomething : function(data) {
if(!data.id)
throw new Meteor.Error(500, "Missing id!");
CollectionName.update({_id:data.id}, {$set: {
'field':value
}});
},
Upvotes: 1