tomcam
tomcam

Reputation: 5285

Meteor.js: Collection.insert works on server but not client

Trying to understand CRUD in Meteor & have a fundamental problem, which is that when I remove auto publish and use explicit pub/sub, collection inserts from the client update the server but not the client collection.

The result is that while the field values are obtained properly, the insert fails on the client side. On the server side, the record is inserted correctly.

$ meteor remove autopublish

Create HTML form file (it's valid and functions as expected), then:

File /server/publish.js:

Meteor.publish('todos'), function() {
    return Todos.find();
}

File /lib/collections.js:

Todos = new Mongo.Collection('todos');

File /client/subscribe.js:

Meteor.subscribe('todos');

File /client/todos.js:

Template.todosList.helpers({
    todosList: function() {
        return Todos.find();
    },
  });

Template.todoNew.events({
    'submit form': function(event) {
        event.preventDefault();
        var theRecord = {
            description: $(event.target).find('[id=description]').val(),
            priority: $(event.target).find('[id=priority]').val()
        };
        // Display correct field values, so form data is OK
        console.log('Attemping to insert: ' + theRecord.description);
        Todos.insert(theRecord, function(error) {
            // This error always occurs
            console.log('error inserting: ' + theRecord.description);
        });
    }
});

Upvotes: 1

Views: 889

Answers (1)

David Weldon
David Weldon

Reputation: 64312

In order to write to a collection from the client you will need an allow rule. Put something like this under /server:

Meteor.publish('todos', function() {
  return Todos.find();
});

Todos.allow({
  insert: function(userId, doc) {
    // a todo must have a description and a priority
    return (doc.description && doc.priority);
  }
});

Upvotes: 1

Related Questions