首页 文章

使用流星方法将表单数据保存到集合中

提问于
浏览
0

使用Meteor我正在尝试使用表单捕获并保存一些数据(名称,电子邮件和年龄) . 此数据应保存在新的Meteor集合“Subscribers”中 . 我的代码如下:

Template Events (client \ views \ subscribe_form \ subscribe_form.js)

Template.Subscribe.events({ 
    'submit form#subscribe-form': function(event){
        // Prevent default browser form submit
        event.preventDefault();

        // Get values from the form
        var subName = $('form#subscribe-form [name=subscribe-name]').val();
        var subEmail = $('form#subscribe-form [name=subscribe-email]').val();
        var subAge = $('form#subscribe-form [name=subscribe-age]').val();

        let subscriberData = {
            name: subName,
            email: subEmail,
            age: subAge,
            createdAt: new Date()
        };

        // Insert subscriber into the collection
        Meteor.call('SubscribeNow', subscriberData, function(error, result){
            if(error){
                // Output error if subscription fails
                console.log(error.reason);
            } else {
                // Success
                console.log("Subscription successful");
                console.log(subscriberData);
                console.log( Subscribers.find() );
            }
        });
    },
});

Server side (server \ collections \ subscribers.js)

var Subscribers = new Meteor.Collection('subscribers');

Subscribers.allow({
    insert: function(){
        return true;
    }
});

Meteor.methods({
    'SubscribeNow': function (subscriberData) {
        //check(subscriberData, String);

        try {
            // Any security checks, such as logged-in user, validating data, etc.
            Subscribers.insert(subscriberData);
        } catch (error) {
            // error handling, just throw an error from here and handle it on client
            if (badThing) {
                throw new Meteor.Error('bad-thing', 'A bad thing happened.');
            }
        }
    }
});

现在,当我向表单添加一些数据并单击提交按钮时,它会通过成功的console.log消息,正确地获取数据,但每当我尝试查询集合时,它都不会显示任何内容 .

我尝试使用我创建的简单模板在集合中查找数据,以便在表格中列出订阅者集合,也使用Meteor Toys和 console.log( Subscribers.find() ); 但没有运气 . 似乎表单已经过,但数据没有保存在集合中 .

enter image description here

此外,删除自动发布和不安全 .

enter image description here

我究竟做错了什么?我对Meteor的所有东西都很陌生,所以它可能是我在这里遗漏的明显事物 .

如果您需要查看更多代码,请告诉我们 . 最后,欢迎任何代码改进建议(结构化等) .

提前谢谢了!

1 回答

  • 1

    因此,根据您添加到问题中的问题和评论, Subscribers 集合数据正在正确保存(您已使用 meteor mongo 验证了这一点),但无法使用 Subscribers.find() 检索数据 . 由于您已删除了 autopublish 包,因此'll have to make sure you'订阅了一个负责将 Subscribers 数据从服务器推送到客户端的出版物 . 例如:

    /server/publications.js

    Meteor.publish('allSubscribers', function () {
      return Subscribers.find();
    });
    

    /client/some_template.js

    Template.someTemplate.onCreated(function () {
      this.subscribe('allSubscribers');
    });
    ...
    

    订阅数据后,可以运行 Subscribers.find() 客户端,并返回数据 .

    有关更多信息,请参阅“流星指南”的Publications and Data Loading部分 .

相关问题