Accessing mongodb collection in Meteor without a template


#1

I have a collection with some data I brought from JSON file: Data.insert( JSON.parse(Assets.getText('data.json')) );. I want to create a var with all the data in a JS file that is not part of a template.

Should I just do var data = Data.find({}).fetch()[0]?
Sometimes the fetch returns empty and I get undefined so I’m guessing this is not the best way. What would be the correct way?


#2

If you just need a single result, use findOne instead of find. That way you don’t have to use fetch.

var data = Data.findOne({});

When it doesn’t find anything I believe it simply returns undefined or an empty object. Can’t recall which one right now.

If you have several objects, you should do an undefined check on data (without the [0]) and then iterate if not undefined.

var data = Data.find({}).fetch();
if(data !== undefined){
 for(var i = 0; i<data.length; i++){
   ...Do what you need to with the objects.
 }
}else{
   ...Do some error handling if needed
}

#3

To insert the data I do Cards.insert( JSON.parse(Assets.getText('cards.json'))) and when I do the query I get an array in which each item is the object I inserted (for each time I re-run this code). so this is why I do [0]

This is what I get without [0]:

[
  {
    _id: "...",
    item1: [....],
    item2: [....]
  },
  {
    _id: "...",
    item1: [....],
    item2: [....]
  }
]

#4

Not quite sure what you’re asking then?