What is the relationship between Collection Hooks and the main db operation?


#1

I am trying to understand how to use the Collection Hooks package. It is not clear to me what the relationship is between the hook and the main db operation.

Is the main db operation performed as part of the hook function? If not, how do I associate the hook with the main db operation?

For example, say I have the following:

Topics = new Mongo.Collection('topics');
SubTopics = new Mongo.Collection('subTopics');

I want to now insert a Topic titled “My Topic” and then after that insert a SubTopic titled “My SubTopic” How would I do that? Where do I pass in the field values for the Topic insert?

This is what I tried but it does not appear to work. Any tips on how to do this correctly would be appreciated. (I read the package docs and the this article and neither, to me, explained this relationship.)

Topics.after.insert(function(itemId,doc, {title: "My Title"} ){

  SubTopics.insert({
    topic: doc._id,
    subTopic: "My SubTopic"
  });

});

Thanks for any advice!


#2
Topics.after.insert(function(itemId,doc, {title: "My Title"} ){

  SubTopics.insert({
    topic: doc._id,
    subTopic: "My SubTopic"
  });

});

Doesn’t look to be valid JS. I think you are confusing Topics.after.insert which is a hook with, Topics.insert which actually inserts into the topics collection.

Topics.after.insert is expecting a function, its called when you insert something into the topic collection.

function (userId, doc, fieldNames, modifier) {
}

So

 Topics.after.insert(function(itemId,doc){

  SubTopics.insert({
    topic: doc._id,
    subTopic: "My SubTopic"
  });

});

Should work. Provided you call Topics.insert() with some data elsewhere your hook will run


#3

Thanks for your response. It’s not clear to me from your response where I insert the actual fields into the Topics collection. Could you please clarify?


#4

With a regular Topics.insert call in some other code, how you would normally insert a document into a collection.

The Topics.insert.after is a hook. It’ll be called at any point once registered. It doesn’t insert anything into the topics collection itself.