Bren Bren - 5 months ago 20
Javascript Question

Array.push() in a Meteor.call() is returning array of index numbers, not ids

I am executing a Meteor method within a

forEach
function, and pushing the result of each method (a new
id
) into an array that is then used for other purposes. I can get see each new
id
created (the
result
from each method). However, the console is returning what appears to be an array of index numbers, rather than an array of new
id
s.

CODE EDITED TO ADDRESS ANSWER BELOW
In event handler, with two documents selected:

var selectionsFinal = [];
selections.forEach(function(v, selectionsFinal) {
Meteor.call('copy', v, function(error, result) {
if(error) {
console.log(error);
} else {
console.log("Result: ", result); //properly returns new id
selectionsFinal.push(result);
console.log("SelectionsFinal: ", selectionsFinal); // properly returns array of 2 new ids
}
});
console.log("SelectionsFinal: ", selectionsFinal); //should return array of new ids, returns []
});
console.log("Selections Final: ", selectionsFinal); //should return array of new ids, returns []


Method

copy: function(v) {
check(v, String);

var valuation = Valuations.findOne({_id:v},{fields:{_id:0});
return Valuations.insert(valuation)
}

Answer

Your pattern is going to be extremely slow and, as you've already discovered, hard to debug. Looping over a Meteor.call() is not recommended because of the numerous server round-trips.

Instead of:

var selectionsFinal = [];
selections.forEach(function(v, selectionsFinal) {
    Meteor.call('copy', v, function(error, result) {})
});

Do:

Meteor.call('bulkCopy',selections,function(error,result){});

Do the array push in the method itself and then return the whole array.