How to show related subdocument properties in Meteor

白昼怎懂夜的黑 提交于 2020-01-25 10:29:06

问题


I am new to Meteor/MongoDB and I'm trying to use something like this to describe a user and his stuff in a meteor project:

{ _id: whatever,
  name: "John Doe",
  myToys: [ {toy_id: "truck",
             quantity: 2},
            {toy_id: "legoset",
             quantity: 4} ]
}

I have another collection that has all those toy_ids and their properties (manufacturer, popularity, etc. and other properties that might change later, which is why I have this in a separate collection).

How would I best code it in meteor and template it to loop through the array of toy subdocuments for a particular user and still display the associated properties of each toy?

Thanks!


回答1:


We can Identify the logged in user with Meteor.userId, so if you stored that id to identify each person's toys in your toys collection so that the user can know which toys are his when using Toys.find({})

You could do this for your template helper.

Template.home.toys = function() {
    return Toys.findOne({user:Meteor.userId});
}

Next you can loop through this in your template using handlebars

<template name="home">
    Name: {{name}}
    {{#each toys.myToys}}
       Toy Id: {{toy_id}}
       Toy Quantity: {{quantity}}
    {{/each}}
</template>


来源:https://stackoverflow.com/questions/15364275/how-to-show-related-subdocument-properties-in-meteor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!