How to extract a particular field from a collection.findOne query result?

Hi
I am trying to extract a particular field from a result of a query

var categoryId = this.props.expensetype.categoryId;
console.log(categoryId); 
var categoryName = Categories.findOne({ _id : categoryId }, {name : 1, slNo : 0, _id : 0});
console.log(categoryName);

I see correct response in the first console message as

"mAprneqZkcgcZrqsv"

The second console log message returns the entire document from the collection Categories.

{_id: "mAprneqZkcgcZrqsv", slNo: 3, name: "Restaurants"} 

I just want to display the “name” field. I thought findOne will reply the corresponding document. How do I do it?

Thanks
Sudheer

Did you try categoryName.name?

Yes. It is “undefined”.

I also tried the “fields” specifier as mentioned in the API docs

var categoryName = Categories.find({ _id : categoryId }, {fields : {name : 1, slNo : 0, _id : 0}});

and it resulted in an error “TypeError: null is not an object (evaluating ‘prevComponentInstance._currentElement’)”

Sudheer

Did you publish the documents already? Looks like if your second console.log worked then you should be able to do categoryName.name.

Your findOne syntax is slightly off (it should look more like the find syntax you posted). Assuming you are subscribed and the documents are available, this will work as expected:

var categoryName = Categories.findOne({ _id : categoryId }, { fields: {name : 1, slNo : 0, _id : 0} } ).name;

@townmulti: Thanks for that tip. I realized my mistake. I was subscribing to the collection in my createContainer. I moved the subscription outside of the class definition and made sure that it was executed before the component was created, and it worked correctly.
@robfallows: I tried that and it gives error “You cannot currently mix including and excluding fields.” Also if you just do “{ fields: {name : 1, slNo : 0, _id : 0} }”, then that also give error saying that “You may not observe a cursor with {fields: {_id: 0}}”. But your rest of the syntax worked correctly.

Thanks guys for all the help. Appreciate it.

Sudheer

1 Like