Reputation: 591
I am using MeteorJS and trying to get the value of a field from MongoDB and assign to a variable. But when want to print to console, it gives all the time 'undefined'. It works fine in HTML template, but i need to store the value in a var in .js file.
var num = ButtonsList.find({_id:'ZcLkjSwNGTpgHkoeq'});
var n = num.button1;
console.log("button number is: "+n);
The code below works fine by the way, if i want them to output in the browser. It outputs the buttons numbers in html using {{}} namespace. But as I said, i need to store the values in variables.
ButtonsList = new Meteor.Collection('list');
Template.theList.helpers({
'buttons': function(){
//return ButtonsList.find().fetch();
return ButtonsList.find('ZcLkjSwNGTpgHkoeq');
}
});
Upvotes: 1
Views: 1238
Reputation: 687
Your using Find , doesnt that mean your getting multiple reccords back? Shouldnt you be using FindOne instead? otherwise youll get an array of objects which means youd have to use num[i].button1 to get to the value.
Upvotes: 1
Reputation: 5108
ButtonsList.find()
returns a cursor.
ButtonsList.find().fetch()
returns an array of buttons.
ButtonsList.findOne()
returns will return a single button.
ButtonsList.findOne().fieldName
will return the field fieldName
of the button that was found.
The reason it works with the {{#each}}
template block helper is that each
blocks know how to iterate over cursors.
Upvotes: 2