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.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With