Reputation: 11039
In Meteor, I have already subscribed to a publications which publishes many documents from a collection. Each document has _id
and name
. I print all these documents somewhere in my app.
On some other place in my app I have some IDs. But instead of printing the ID, I want to print the name which corresponds to the id.
I could simply use
for (var i=0; i<idList.length; i++) {
doc = CollectionName.findOne(idList[i]);
console.log(doc.name);
}
but will this result in poor performance? I am thinking that since I have already subscribed to the entire collection, it wont cost more to perform a mongodb call for each id. Am I wrong?
Upvotes: 0
Views: 53
Reputation: 6974
On the client all your queries are made against the MiniMongo database (which is an client side in-memory replication of MongoDB) containing the documents published by the server. So it is really cost effective as you are searching for documents only on the client side without calling the server.
Concerning your code, I think the use of find()
and then map()
would be more effective:
var namesArray = CollectionName.find().map(function(document) {
console.log(document.name);
return document.name;
});
With find()
you are doing only one query that returns a cursor, then the map()
function will go through all the documents in the cursor and perform whatever operation you want with each document like printing the name in the console and returning it.
Also, all returned values will be added to a single array (here called namesArray
) that you will be able to reuse somewhere else.
Upvotes: 1