How do you use fetch() and get only certain document fields vs. retrieving all of it? [Resolved]


#1

Probably a very straight forward answer, but here’s my template event:

'click .export-data': function() {
    var rawData = Lot.find({
      vacant: false
    }).fetch();
    console.log(rawData);
    csv = json2csv(rawData, true, true);
    var blob = new Blob([csv], {
      type: "text/plain;charset=utf-8;",
    });

    saveAs(blob, "lot-readings.csv");
  }

It’s a very basic collection and operation – you click a button, and out spits a csv file. As it is right there, it’ll dump every value from a document into columns/rows, but I only need two things: lotNumber and reading. Here’s an example of a doc:

{ 
    "_id" : "fWx792DwhDbb26MMM", 
    "lotNumber" : NumberInt(128), 
    "vacant" : false, 
    "reading" : "1234567890", 
    "lastUpdatedAt" : 1470503941501.0
}

What I’d like to do is take rawData and flip the cursor of objects to only contain those two fields (lotNumber and reading).

I checked the docs for fetch() but can’t seem to find anything on how to scope down what is returned. Help would be appreciated! :slight_smile:

[Update]
I can do something like this –

  var rawData = Lot.find({
      vacant: false
    }).fetch().map(function(obj){
      return obj.lotNumber
      });
    console.log(rawData); 

Which dumps a single property off of the cursor for each document in the array, but when I download the csv file, I’d expect to see a single column of lotNumber's but it comes out blank. Strange?


#2

It should work with something like this:

var rawData = Lot.find({
  vacant: false
}, {
  _id: 0,
  lastUpdatedAt: 0,
  vacant: 0
}).fetch();

I dont know if you can omit _id but you can give it a try.

Source


#3

I believe with Meteor you need to specify the fields in the options (docs)

var rawData = Lot.find({
 vacant: false
}, {
 fields: {
  lastUpdatedAt: 0,
  vacant:0,
 }
}).fetch();

#4

@jamgold && @jhuenges you both are spot on! Export only contains the info I need

By the way @jhuenges I gave it a go without _id and it works just fine. Pretty killer.

Thanks a lot fellas, this will be super helpful in the future whenever trying to get specific info out of docs from *.fetch().