简体   繁体   中英

Meteor JS: How to use Spacebars to display contents inside an array retrieved from Meteor Collection

I have a collection:

MenuItems = new Mongo.Collection('menu_items');

and I also have an array:

var arrayToInsert = ['Gemstone', 'Rings'];

I then insert this array into the collection via:

MenuItems.insert(arrayToInsert);

The resulting document inside my mongodb as shown in RoboMongo is:

{
    "_id" : "yRXmFGxLCZXLf9Ynh",
    "0" : "Gemstone",
    "1" : "Rings"
}

In my Template Helper I have:

menuItems: function(){
    return MenuItems.find();
  },

In my .html file I do this:

{{#each menuItems}}
  {{this}}
{{/each}}

But I only get this output:

[object Object]

How do I use Spacebars to iterate through this array of data so I may get it to display 'Gemstone' and 'Rings'????

Thank you very much.

If you want the array to represent the menu items value, you should insert them into the collection like this :

arrayToInsert.forEach(function(menuItem){
  MenuItems.insert({
    label: menuItem
  });
});

Then you can display the menu items in your template :

JS

Template.menu.helpers(function(){
  menuItems: function(){
    return MenuItems.find();
  }
});

HTML

<template name="menu">
  <ul>
    {{#each menuItems}}
      <li>{{label}}</li>
    {{/each}}
  </ul>
</template>

If you want to store the array as part of the collection documents, use this code :

JS

MenuItems.insert({
  items:arrayToInsert
});

HTML

<template name="menu">
  {{#each menuItems}}
    <ul>
      {{#each items}}
        <li>{{this}}</li>
      {{/each}}
    </ul>
  {{/each}}
</template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM