我有两个系列,我想仅显示已点击的产品的评论,但无论我点击什么产品,我都会收到所有评论(来自评论集)。 为了添加和阅读评论,我在router.js
中有以下代码 // Add new review
this.route('add_review', {
path:'/add_review/:_id',
template:'add_review',
data: function(){
return Products.findOne(this.params._id)
}
});
// Read reviews
this.route('reviews', {
path:'/reviews/:_id',
template:'reviews',
data: function(){
return Products.findOne(this.params._id)
}
});
});
reviews.js
Template.reviews.helpers({
'reviews': function () {
return Reviews.find( )}
})
reviews.html
<template name="reviews">
<div class="row product-row">
<div class="col-md-2">
<img class="full" src="{{image}}">
</div>
<div class="col-md-10">
<h4>{{name}}</h4>
<p>{{description}}</p>
</div>
</div>
{{#each reviews}}
<p>{{body}} </p>
{{/each}}
</template>
上找到项目的完整代码
答案 0 :(得分:4)
查看源代码后。您似乎没有在数据库中保存产品和评论之间的任何关联。您希望将产品_id
存储在评论对象的某个位置。完成后,您将能够在模板中按productId过滤评论。我在下面写了一些示例代码。
<强> add_review.js 强>
Template.add_review.events({
'submit .add_review':function(event){
var rating = event.target.rating.value;
var body = event.target.body.value;
if(body!=""){
Reviews.insert({
rating:rating,
body:body,
productId:Router.current().data()._id //access the product's _id here and save it in this field
});
FlashMessages.sendSuccess('Review Added',{ autoHide: true, hideDelay: 3000 });
Router.go('/');
}
else{
alert('Review field is empty');
}
return false;
}
})
<强> reviews.js 强>
Template.reviews.helpers({
'reviews': function () {
return Reviews.find({productId: Router.current().data()._id}) // again, access the products _id from the router
}
})