Reputation: 337
I'd like to send an email every time a new document is added to a given collection. Is subscribing to a collection from the server side the right way to do this with Meteor?
Publish/subscribe give a way to attach observers to subscriptions, but this only seem to monitor connections from the client, not the collection itself ("add" gets called with the whole collection content when a client connects to it).
Upvotes: 1
Views: 1117
Reputation: 9486
I don't think so. But there is a good way using YourCollection.deny()
:
On the server:
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;
}
});
});
If the client inserts an item into YourCollection the server checks whether he is allowed by first running all deny functions until one returns true and else all of the allow rules unless one of them returns true.
If at least one allow callback allows the write, and no deny callbacks deny the write, then the write is allowed to proceed. -- Meteor Doc.
Notice that you cannot use YourCollection.allow() for what you want, as it will not necessarily run (if there is no deny one allow is sufficient).
But take care: If you use the insecure package which you do by default, everything will be allowed unless you setup your own rules. As you just did this, you probably want to allow the insert now by adding
YourCollection.allow({
insert: function (userId, item) {return true;},
update: function (userId, item) {return true;},
remove: function (userId, item) {return true;}
});
next to the deny function.
-best, Jan
Upvotes: 1
Reputation: 12085
The correct way to do this would be to add a server method using Meteor.methods(). The documentation for that is here: http://docs.meteor.com/#meteor_methods .
To send the email you're going to need to make a request to another server as meteor has no built in email sending yet. The docs for making http requests are here: http://docs.meteor.com/#meteor_http_post .
Small example:
Meteor.methods(
create_document: function (options) {
//insert the document
//send a post request to another server to send the email
}
)
Then on the client you would call:
Meteor.call("create_document", <your options>);
Upvotes: 3