如何使用 Meteor 监视服务器对集合的更改

How to monitor changes to a collection from the server with Meteor?

本文关键字:集合 服务器 何使用 Meteor 监视      更新时间:2023-09-26
我想在

每次将新文档添加到给定集合时发送电子邮件。从服务器端订阅集合是使用 Meteor 执行此操作的正确方法吗?

发布/订阅提供了一种将观察者附加到订阅的方法,但这似乎只监视来自客户端的连接,而不是集合本身(当客户端连接到集合内容时,会调用整个集合内容"add")。

正确的方法是使用 Meteor.methods() 添加一个服务器方法。这方面的文档在这里: http://docs.meteor.com/#meteor_methods .

要发送电子邮件,您需要向另一台服务器发出请求,因为meteor还没有内置的电子邮件发送功能。发出 http 请求的文档在这里: http://docs.meteor.com/#meteor_http_post .

小例子:

Meteor.methods(
  create_document: function (options) {
    //insert the document
    //send a post request to another server to send the email
  }
)

然后在客户端上调用:

Meteor.call("create_document", <your options>);

我不这么认为。但是有一个使用YourCollection.deny()的好方法:

在服务器上:

Meteor.startup(function(){
  YourCollection.deny({
    insert: function (userId, item) {
      // Send your Email here, preferential 
      // in a asynchronous way to not slow down the insert
      return false;
    }
  });
});

如果客户端将项目插入 YourCollection,服务器会首先运行所有拒绝函数(直到一个函数返回 true)来检查是否允许他,否则所有允许规则,除非其中一个函数返回 true。

如果至少有一个允许回调允许写入,并且没有拒绝回调拒绝写入,则允许写入继续。

请注意,您不能将 YourCollection.allow() 用于您想要的内容,因为它不一定会运行(如果没有拒绝,则一个允许就足够了)。

但要小心:如果您使用默认使用的不安全软件包,除非您设置自己的规则,否则一切都将被允许。正如您刚刚执行此操作时,您可能希望现在通过添加

YourCollection.allow({
  insert: function (userId, item) {return true;},
  update: function (userId, item) {return true;},
  remove: function (userId, item) {return true;}
});

旁边的拒绝函数。
-最佳,一月