funkyeah funkyeah - 4 months ago 26
CoffeeScript Question

how to manipulate returned mongo collections / cursors in javascript (meteor.js)?

In working with Meteor.js and Mongo I use the find({some arguments}) and sometimes find({some arguments}).fetch() to return cursors and an array of matching documents respectively.

What is the real difference between the two? (when would I use one versus the other?)

What is the proper way to manipulate/iterate over these type of returned objects?

I have a collection that has many documents each with a title field.

My goal was to get an array of all the title fields' values e.g. [doc1title,doc2title,doc3title]

I did this:

var i, listTitles, names, _i, _len;
names = Entries.find({}).fetch();
listTitles = [];
for (_i = 0, _len = names.length; _i < _len; _i++) {
i = names[_i];

or the equivalent in coffeescript

names = Entries.find({}).fetch()
listTitles = []
for i in names

which works, but I have no idea if its the proper way or even a semi sane way.


Your first question has been asked before - also see this post. The short answer is that you want to use the cursor returned by find unless you really need all of the data at once in order to manipulate it before sending it to a template.

Your CoffeeScript could be rewritten as:

titles = (entry.title for entry in Entries.find().fetch())

If you are using underscore, it could also be written as:

titles = _.pluck Entries.find().fetch(), 'title'