user1532669
user1532669

Reputation: 2378

Meteor: how do I create a post insert hook?

I'm using autoform to create forms. I have the template below which is correctly inserting data into the collection when the form is submitted. What I want to do is insert a record into another collection when the insert into the "ContactDetails" collection has been completed successfully.

<template name="contactDetailsForm">
 {{#if submitted}}
    {{> quickForm collection="ContactDetails" omitFields="createdBy" doc=editingDoc id="contactDetailsForm" type="update"}}
 {{else}}
         {{> quickForm collection="ContactDetails" omitFields="createdBy" id="contactDetailsForm" type="insert"}}
 {{/if}}
</template>

As far as I know I would need to add a hook. I'm really not sure what I'm doing with this. I'd imagine it would look something like this:

  AutoForm.addHooks(['contactDetailsForm'], {
    after: {
      insert: function(error, result) {
        if (error) {
        console.log("Insert Error:", error);
        } else {
        console.log("Insert Result:", result);
        // NOW DO INSERT INTO OTHER COLLECTION
        }
      }
    }
});

Can anyone show me how to insert a record into another collection after an insert has been successfully completed in a different collection?

Any advice/help/examples on this would be sincerely appreciated.

Upvotes: 2

Views: 1808

Answers (2)

Hubert OG
Hubert OG

Reputation: 19544

The matb33:collection-hooks package is a standard way to create such hooks. First add it with

meteor add matb33:collection-hooks

Then create your hook:

ContactDetails.after.insert(function(userId, doc) {
  console.log("Inserted:", this._id);
  ...
});

Upvotes: 3

Rune Jeppesen
Rune Jeppesen

Reputation: 1131

In general the hooks are not available yet - but they are in autoform: https://github.com/aldeed/meteor-autoform#callbackshooks

If you were not using autoform I would do the insert with a Meteor method, where you could just do the after insert, after you inserted the first one. See this https://www.discovermeteor.com/blog/meteor-methods-client-side-operations/

Upvotes: 1

Related Questions