Search code examples
javascriptmeteor

Meteor cursor.map(): GOTCHA How do I extract just one element multiple times?


How do I use the map function for a meteor collection?

http://docs.meteor.com/#map

Using a tutorial, we have a collection called Posts.

Posts.find() returns a cursor which lets me iterate over all the Posts.find().fetch() will give me an array of all the posts, but this might be a lot of data.

Suppose I just want one element of Posts, like the titles, in an array: I can do this:

titles=Posts.find().map(function(a) {return a.title}); // works

Suppose I want the title and the ownerIds. I was debugging this and did:

a=Posts.find()
titles=a.map((function(a) {return a.title;}); // works
ownerIds=a.map((function(a) {return a.ownerId;}); //doesn't work, cursor already iterated over, returns empty array.

This does not work. Why?


Solution

  • You can use a cursor more than once by calling rewind on it. From the docs:

    The forEach, map, or fetch methods can only be called once on a cursor. To access the data in a cursor more than once, use rewind to reset the cursor.

    So this should work:

    a=Posts.find()
    titles=a.map((function(a) {return a.title;});
    a.rewind();
    ownerIds=a.map((function(a) {return a.ownerId;});