2
我想製作一個像按鈕一樣喜歡食譜,並將喜歡食譜的所有用戶ID添加到數組中選民和更高版本想通過使用._contains多次喜歡同一食譜的用戶同樣的用戶仍然能夠多次喜歡它。你能幫我解決我犯的錯誤嗎?Like流星按鈕
完整的源代碼Github
Template.recipes.events({
"click [data-action='addLikes']": function (event) {
event.preventDefault();
if (_.contains(Recipes.voters, Meteor.userId()))
FlashMessages.sendError("You already liked this recipe", {hideDelay: 1000});
Recipes.update(this._id, {$addToSet: {voters: Meteor.userId()}, $inc: {likes: 1}});
}
});
collections.html
Recipes = new Mongo.Collection('recipes');
Recipes.attachSchema(new SimpleSchema({
ownerId: {
type: String
},
ownerName: {
type: String
},
voters:{
type:Array,
optional:true
},
'voters.$':{
type:String
},
name: {
type: String,
label: "Recipe Name",
max: 100
},
ingredients: {
type: [Object],
minCount: 1
},
"ingredients.$.name": {
type: String
},
"ingredients.$.amount": {
type: String
},
description: {
type: String,
label: "How to prepare ",
},
time: {
type: Number,
label: "Time (Minutes)",
min:0
},
likes:{
type:Number,
optional:true
},
image: {
type: String,
autoform: {
afFieldInput: {
type: "cfs-file",
collection: 'recipesImages',
label: 'Recipe Picture'
}
}
}
}));
add_recipes.html
<template name="add_recipes">
<div class="container">
{{#autoForm collection="Recipes" id="insertRecipes" type="insert"}}
<fieldset>
<legend>Add a Recipe</legend>
{{> afQuickField name='name'}}
{{> afQuickField name='ingredients'}}
{{> afQuickField name='description' rows=6}}
{{> afQuickField name='time'}}
{{> afQuickField name="image" }}
{{> afQuickField name="likes" value="0" type="hidden" }}
{{> afQuickField name='ownerId' type="hidden" value=currentUserId}}
{{> afQuickField name='ownerName' type="hidden" value=currentUserName}}
{{> afQuickField name='voters' type="hidden" value=""}}
</fieldset>
<button type="submit" class="btn btn-primary">Add Recipe</button>
{{/autoForm}}
</div>
發送錯誤消息後,我們必須返回false,否則它仍然會添加類似內容。 @Stephen伍茲 – Waqar