I am trying to implement the .allow part of meteor in an application I'm building. Before introducing it a list was displaying comments a user entered, now the comments just flash up for a second and then disappear. The comments are still being added to the collection though. Could anyone tell me what I'm doing wrong, I am very new to this.
Main js file:
if (Meteor.isClient) {
Meteor.startup(function () {
Meteor.subscribe("ques");
});
Template.compose.events({
'submit form': function (event) {
var $body = $('#que-body');
var $score = 1;
event.preventDefault();
Questions.insert({
body: $body.val(),
score: $score,
created_at: Date()
});
$body.val('');
}
});
Template.question.selected = function () {
return Session.equals("selected_question", this._id) ? "selected" : '';
};
Template.question.events({
'click': function () {
Session.set("selected_question", this._id);
}
});
Template.question.que = function(){
return Questions.findOne(Session.get("selected"));
};
// Deals with up-vote, down-vote, remove buttons
Template.list.events({
'click .icon-thumbs-up': function(event) {
Questions.update(Session.get("selected_question"), {$inc: {score: 1}});
},
'click .icon-thumbs-down': function(event) {
Questions.update(Session.get("selected_question"), {$inc: {score: -1}});
},
'click .icon-remove': function(event) {
Questions.remove(Session.get("selected_question"));
}
});
Template.list.questions = Questions.find({}, {sort: {score: -1, created_at: -1}});
}
if (Meteor.isServer) {
Meteor.startup(function () {
Meteor.publish("ques", function(){
return Questions.find({}, {
fields:{ }
})
});
});
}
The model.js file:
Questions = new Meteor.Collection("questions");
Questions.allow({
insert: function(userId, que){
return userId && que.owner === userId;
},
update: function(id, ques, fields, modifier){
return true;
},
remove: function(id, que){
return id && que.owner === id;
}
});
Do you mean the questions (you said comments?): Your Meteor.allow rule is basically something that says the question.owner is the current logged in user's _id. You need to insert an owner when you insert your question. This is the only way (que.owner === userId will return true):
Questions.insert({
owner: Meteor.userId(),
body: $body.val(),
score: $score,
created_at: Date()
});
Make sure you ensure that only logged in users have the chance to insert questions. Either by hiding the button or having a check just before everything is inserted too:
if(!Meteor.userId()) {
alert("You need to be logged in to post a question");
return;
}