[英]How do I return document property from document in another collection by ID using Meteor?
I have two collections: Products and Category. 我有两个集合:“产品”和“类别”。 The insertion of both is working fine.
两者的插入工作正常。 My problem is returning the name of a category in products list.
我的问题是在产品列表中返回类别的名称。 It's listing with _id from Category.
它用类别中的_id列出。 I need its name.
我需要它的名字。
Here is Products collections: 这是产品集合:
Products = new Meteor.Collection('products');
/*
* Add query methods like this:
* Products.findPublic = function () {
* return Products.find({is_public: true});
* }
*/
var Schema = {};
Schema.Products = new SimpleSchema({
name: {
type: String,
label: "Nome",
optional: false
},
category: {
type: Schema.Categories,
optional: false
},
"category.$.name": {
type: String
},
subcategory: {
type: Schema.Subcategories,
optional: true
},
"subcategory.$.name": {
type: String
},
description: {
type: String,
label: "Descrição",
optional: true,
max: 150
}
});
Products.attachSchema(Schema.Products);
Products helper to list them: 产品助手列出他们:
Template.Products.helpers({
// Return all products
list: function() {
return Products.find({}, {
sort: {
time: -1
},
fields: {
name: true,
category: true,
subcategory: true
}
}).fetch();
}
});
And Products template: 和产品模板:
<template name="Products">
<fieldset>
<legend>
<p class="pull-left">
Produtos
</p>
<a href="{{pathFor 'ProductsNew'}}" class="btn pull-right btn-success btn-sm">Novo Cadastro</a>
<div class="clearfix"></div>
</legend>
<table class="table">
<thead>
<tr>
<th>Nome</th>
<th>Categoria</th>
<th>Subcategoria</th>
<th></th>
</tr>
</thead>
<tbody>
{{#each list}}
<tr>
<td>{{name}}</td>
<td>{{category}}</td>
<td>{{subcategory}}</td>
<td>
<a href="{{pathFor 'ProductsEdit' _id }}" class="btn btn-xs btn-primary">Editar</a>
</td>
<td>
<button class="destroy btn btn-danger btn-xs">Delete</button>
</td>
</tr>
{{/each}}
</tbody>
</table>
</fieldset>
</template>
How can I do that? 我怎样才能做到这一点?
Here is an image of my problem: 这是我的问题的图片:
David is right. 大卫是对的。 A single product example would be helpful.
单个产品示例将很有帮助。 It's hard to understand what you are trying to do.
很难理解您要做什么。 But my best guess is this:
但我最大的猜测是:
In your template try 在您的模板中尝试
<td>{{categoryName}}</td>
<td>{{subcategoryName}}</td>
And in your js 在你的js里
Template.Products.categoryName = function() {
var _category = Categories.findOne({_id: this.category});
return _category ? _category.name : "";
}
Template.Products.subcategoryName = function() {
var _subcategory = Subcategories.findOne({_id: this.subcategory});
return _subcategory ? _subcategory.name : "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.