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

14,860

Solution 1

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'

Solution 2

To iterate over a cursor in js simply use cursor.forEach

const cursor = Collection.find();
cursor.forEach(function(doc){
  console.log(doc._id);
});

When converting cursors to arrays you will also find the .map() function useful:

const names = Entries.find();
let listTitles = names.map(doc => { return doc.title });
Share:
14,860
funkyeah
Author by

funkyeah

Updated on June 29, 2022

Comments

  • funkyeah
    funkyeah almost 2 years

    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?

    E.g. 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];
        listTitles.push(i.title);
    }
    

    or the equivalent in coffeescript

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

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

  • Godsmith
    Godsmith over 8 years
    Thanks for the link to the meteor docs. As a side note, why oh why did they invent the name fetch() for creating an array from a cursor when it is called toArray() in normal Mongo. It took me a good while to figure out that I did not possess a normal Mongo cursor but instead a meteor variant.