【问题标题】:Create document after submit with meteor-autoform使用meteor-autoform提交后创建文档
【发布时间】:2015-09-15 06:12:57
【问题描述】:

我正在使用meteor-autoform。我用

创建我的表单
{{> quickForm collection="Messages" id="insertMessageForm" type="insert" fields="text"}}

它按应有的方式插入消息,但我还想在 Notification 集合中创建一个文档。如何确保每次创建新消息时都会创建通知?每次在我的应用程序的集合中创建新文档时,我都想创建通知。如何最聪明地做到这一点?我可以创建一个 afterCreate 信号吗?

【问题讨论】:

    标签: javascript node.js meteor meteor-autoform


    【解决方案1】:

    使用流星核心功能cursor.obsere

    lib/

    Messages.observe({
      added: function (doc) {
        Notifications.insert({ text: 'New Message: ' + doc.text })
      }
    })
    

    doc 变量保存插入的新文档。

    【讨论】:

    • 谢谢。我正在使用Notifications.insert({userId: this.userId, text: 'New Message: ' + doc.text, createdAt: new Date});,但似乎this.userId 是空的。我应该在哪里放置代码以及如何获取用户 ID?我也试过Meteor.user(),但后来我收到错误Exception in queued task: Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions
    • 对不起,我更新了我的答案。 server/ 是放置它的地方。要获取用户 ID,您可以使用 Meteor.userId()
    • 在一个名为observe.js的文件中?看来我应该使用Messages.find().observe() 而不是Messages.observe()。对吗?
    • 即使我已经将代码放在server/observe.js 中,使用Meteor.userId() 时仍然收到错误Exception in queued task: Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.
    • 抱歉,我错误地认为Meteor.userId 可以在任何地方调用。您必须将观察者放入client/
    【解决方案2】:

    我想在每次在 在我的应用中收集。

    那么你应该使用这个包:matb33:collection-hooks

    您将能够为每个集合创建挂钩,以便在插入新文档时创建通知。

    Comments.after.insert(function(userId, comment){
      Notifications.insert({
        userId: userId,
        text: comment.text,
        createdAt: comment.createdAt
      });
    });
    

    使用这个包时要小心,不要过度复杂化你的应用程序逻辑并创建循环钩子。

    【讨论】:

    • 当一个包很容易使用核心包的特性时,为什么还要使用它? cursor.observe 正是他们想做的事。这个包是否比核心功能有任何好处?
    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 2017-05-09
    • 2016-12-04
    • 2015-07-06
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    相关资源
    最近更新 更多