Each answer document in the Answers
collection can be looped through using the forEach()
method to find the corresponding user document in the Users
collection based on the ID, illustrated below:
Answers = new Meteor.Collection("answers");
Users = new Meteor.Collection("users");
if(Meteor.isClient) {
processed_data = [];
Deps.autorun(function (c) {
console.log('run');
var cursor = Answers.find({}, { sort: { time: 1 }});
if (!cursor.count()) return;
cursor.forEach(function (ans) {
var user = Users.findOne({ "_id": ans.user }, { "fields": {"firstname": 1, "surname": 1} });
ans.user = user;
processed_data.push(ans);
});
console.log(processed_data);
c.stop();
});
}
The data will stay reactive as Deps.autorun ensures that the block inside function() {...}
is re-executed whenever there's any change in a reactive variable or document, like updates, removals, inserts, or other reactive changes.
To update the userId
in the Answers
collection with the actual user document containing firstname and surname, you can leverage the Bulk API operations for efficient updates. Access the raw collection and database objects via rawCollection()
and rawDatabase()
methods on Mongo.Collection
.
Answers = new Meteor.Collection("answers");
Users = new Meteor.Collection("users");
if (Meteor.isClient) {
Template.answerlist.helpers({
answers: function () {
processed_data = [];
Deps.autorun(function (c) {
console.log('run');
var cursor = Answers.find({}, { sort: { time: 1 }});
if (!cursor.count()) return;
cursor.forEach(function (ans) {
var user = Users.findOne({ "_id": ans.user }, { "fields": {"firstname": 1, "surname": 1} });
ans.user = user;
processed_data.push(ans);
});
console.log(processed_data);
c.stop();
});
return processed_data;
}
});
Template.answerlist.events({
'click #updateAnswers': function(ev) {
Meteor.call('updateAnswersUser');
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
Meteor.methods({
updateAnswersUser: function() {
var bulkOp = Answers.rawCollection().initializeUnorderedBulkOp(),
counter = 0;
Answers.find({}).forEach(function(ans) {
var user = Users.findOne({ "_id": ans.user }, { "fields": {"firstname": 1, "surname": 1} });
var changes = {};
changes["user"] = user;
bulkOp.find({"_id": ans._id}).updateOne({ "$set": changes });
counter++;
if (counter % 1000 == 0) {
// Execute per 1000 operations and re-initialize every 1000 update statements
bulkOp.execute(function(e, r) {
console.info('r.nMatched', r.nMatched, 'r.nModified', r.nModified);
});
bulkOp = Answers.rawCollection().initializeUnorderedBulkOp();
}
});
// Clean up queues
if (counter % 1000 != 0){
bulkOp.execute(function(e, r) {
console.info('r.nMatched', r.nMatched, 'r.nModified', r.nModified);
});
}
}
});
});
}