Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 673
funkyeah Avatar asked May 22 '13 03:05

funkyeah


1 Answers

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 });
like image 106
Michel Floyd Avatar answered Sep 28 '22 06:09

Michel Floyd