【问题标题】:Meteor.js: Collection.insert works on server but not clientMeteor.js:Collection.insert 适用于服务器但不适用于客户端
【发布时间】:2014-12-06 08:19:29
【问题描述】:

试图理解 Meteor 中的 CRUD 并遇到一个基本问题,即当我删除自动发布并使用显式发布/订阅时,来自客户端的集合插入会更新服务器而不是客户端集合。

结果是,虽然正确获取了字段值,但在客户端插入失败。在服务器端,记录插入正确。

$meteor remove autopublish

创建 HTML 表单文件(它是有效的并按预期运行),然后:

文件 /server/publish.js:

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

文件 /lib/collections.js:

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

文件 /client/subscribe.js:

Meteor.subscribe('todos');

文件 /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);
        });
    }
});

【问题讨论】:

    标签: meteor


    【解决方案1】:

    为了从客户端写入集合,您需要一个allow 规则。在/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);
      }
    });
    

    【讨论】:

    • 非常感谢 - 我仍然无法让它工作。我尝试了几个不同的版本,它们导致运行时错误如下:调用方法'/todos/insert'时出现异常类型错误:无法读取null的属性'描述'这是我的尝试:文件 /server/publish.hs: ` Todos.allow({ insert: function (userId, doc) { return (doc.description && doc.priority); } }); ` And: 文件 /server/publish.hs: ` Todos.allow({ insert: function (theRecord) { return (theRecord.description && theRecord.priority); } });
    • @tomcam,第一个参数是用户的id(或者null,如果用户没有登录),第二个参数存储文档。
    • 这么想,@peppe-l-g,感谢您的回复!因此,我的第二个版本也不起作用。我在添加帐户-ui 时特意删除了自动发布。在我看来,pub/sub 在技术上与accounts-ui 无关,当然实际上它应该在任何有价值的应用程序中。我错了吗?删除自动发布时是否总是需要添加帐户 UI?
    • accounts-uiautopublish 可以相互独立安装。我更新了答案。您的错误表明 docundefined 我认为这是不可能的。或者,您可以尝试从函数中返回 true (尽管您的架构没有被检查)。如果所有这些仍然不起作用,请将您的代码放在 meteorpad 或我可以查看的 github 存储库中。
    • 谢谢你,@DavidWeldon。我不知道 Meteorpad。我把它放在(meteorpad.com/pad/aNfQ9gsT5QjT3BEbo)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2011-09-28
    • 2017-09-01
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多