Return a value from a returned object mongodb/blaze?


#1

This should be basic but i can’t find how to do it online. I have a collection that i am returning to a blaze template and i want the specific value to display:

in the JS file I have:

Template.display.helpers({
 showIt(){
     return Profiler.find({}); //
}
});

there is only 1 document in this collection at any given time. this is because the collection is filtered at the server and sent back with only 1 document in it. in the collection i have the following:

_id: sd89f234kjfddsf
firstName: Joe
lastName: Smith

In the HTML File

<Template name="display">
  {{showIt.firstName}}
</template>

trying to get “Joe” to display but how?


#2

Your helper is returning a cursor, so you need to loop through the results, even if there is only one:

<template name="display">
  {{#each showIt}}
    {{firstName}}
  {{/each}}
</template>

#3

hmm is there a way to return the value directly when performing the find({}) in the JS and saving it to a variable?


#4

I’m not sure I understand the use case?

If you are trying to access the returned docs in your JS, you can create an array of objects with the following code: Collection.find({}).fetch();

If you know the _id of the doc, you can get an object using: Collection.findOne({ _id });


#5

Like @vigorwebsolutions said, use findOne(). You should pass the query an id, but if you are saying that there is only ever that single document being published, it should work.

so just make a helper {{firstName}}

firstName() {
  return Profiler.findOne().firstName
}

or use {{#with}}

{{#with profile}}
  {{firstName}}
  {{lastName}}
{{/with}}

and the js…

profile() {
  return Profiler.findOne();
}

#6

thanks guys i will try this out.