[英]How do I return document property from document in another collection by ID using Meteor?
我有兩個集合:“產品”和“類別”。 兩者的插入工作正常。 我的問題是在產品列表中返回類別的名稱。 它用類別中的_id列出。 我需要它的名字。
這是產品集合:
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);
產品助手列出他們:
Template.Products.helpers({
// Return all products
list: function() {
return Products.find({}, {
sort: {
time: -1
},
fields: {
name: true,
category: true,
subcategory: true
}
}).fetch();
}
});
和產品模板:
<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>
我怎樣才能做到這一點?
這是我的問題的圖片:
大衛是對的。 單個產品示例將很有幫助。 很難理解您要做什么。 但我最大的猜測是:
在您的模板中嘗試
<td>{{categoryName}}</td>
<td>{{subcategoryName}}</td>
在你的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.