What's better - collection.forEach or collection.map?

hi,

the process i want to create is built from two parts:

  1. to each user on my users collection i have added an object with facebook friends ids (those are the facebook ids of the friends of the user). it looks like that:
"facebook_friends" : [
		{
			"name" : "[name]",
			"id" : "[id]"
		},
		{
			"name" : "[name2]",
			"id" : "[id2]"
		}
	]

in addition, i created an index collection matching facebook ids and meteor user ids for each of the app users (on this collection will appear all of my users, and not only those of the user):

{ "_id" : "[id]", "facebookId" : "[facebook_id]", "meteorId" : "[meteor_id]" }

now i want to loop over each friend from the first list (according to facebook id), find its match on the second list, and according to that insert an array of meteor ids into the user’s user object.

the idea is that i want to insert all of the meteor ids i’ll get back, and insert them as a single array (one array with all the meteor ids).
what would you recommend - collection.forEach or collection.map? can you explain why?

To be honest, for anything but a trivial lookup I’d use an aggregation pipeline. If you really want to do this in your server code you could use either forEach or map. However, map sounds like it’s more functionally correct for your use case.

2 Likes