4

I am trying to run certain insert statements after a collection has been updated. For example, if a user adds an embedded document Location to their User document, I would like to also insert that embedded document into a separate Location collection. Is there a way to do this on the server side so that the operation is guaranteed to run?

HGandhi
  • 1,586
  • 2
  • 14
  • 27
  • I am aware that you can call a method server side to do both the update and insert, but that would have the negative consequence of removing latency compensation from what I understand. – HGandhi Oct 30 '12 at 17:15

2 Answers2

3

If you're willing to use some code I wrote (https://gist.github.com/matb33/5258260), you can hook in like so:

EDIT: code is now part of a project at https://github.com/matb33/meteor-collection-hooks

var test = new Meteor.Collection("test");

if (Meteor.isServer) {
    test.before("insert", function (userId, doc) {
        doc.created = doc.created || Date.now();
    });

    test.before("update", function (userId, selector, modifier, options) {
        if (!modifier.$set) modifier.$set = {};
        modifier.$set.modified = Date.now();
    });

    test.after("update", function (userId, selector, modifier, options, previous) {
        doSomething();
    });
}
Mike Marcacci
  • 1,913
  • 1
  • 18
  • 24
matb33
  • 2,820
  • 1
  • 19
  • 28
-1

you would need to do it in a method.. you can keep latency compensation by implementing a client-side Method stub:

Calling methods on the client defines stub functions associated with server methods of the same name. You don't have to define a stub for your method if you don't want to. In that case, method calls are just like remote procedure calls in other systems, and you'll have to wait for the results from the server.

If you do define a stub, when a client invokes a server method it will also run its stub in parallel. On the client, the return value of a stub is ignored. Stubs are run for their side-effects: they are intended to simulate the result of what the server's method will do, but without waiting for the round trip delay. If a stub throws an exception it will be logged to the console.

see my Meteor stub example here: https://stackoverflow.com/a/13145432/1029644

Community
  • 1
  • 1
Lloyd
  • 8,204
  • 2
  • 38
  • 53
  • Do you have example of how to implement said stubs? I am looking at some examples on StackOverflow such as [this one](http://stackoverflow.com/questions/12231712/when-to-use-meteor-methods-and-utilizing-stubs) but I am still a little confused as to how to implement this. – HGandhi Oct 30 '12 at 17:58