← back to code snippets


Vulcan.JS: Insert a document into any collection after a user created

Posted on December 23rd, 2019 in JavaScript by Graeme

After creating a user, I wanted to assign them to a new 'publication' collection for their documents, instead of restricting documents created to the user's account. This way, every user starts with their own single publication, but can also create new ones, or be assigned to existing ones.

Here's how I create a new publication when a user is added:

 

In my Publications collection (similar to the movies collection in the Vulcan example), there's a parameters.js file. In there you can add a new callback. The callback triggrered after a user is created is user.create.async

import { addCallback, withCreate } from 'meteor/vulcan:core';
import Publications from "./collection.js";


function sortbyDate (parameters, terms) {
return {
selector: parameters.selector,
options: {...parameters.options, sort: {date: -1}}
};
}

addCallback('publication.parameters', sortbyDate);


function insertPublicationAfterUserCreated (data, properties){

console.log('inserting new publication')

Publications.insert({ name: 'New Publication', desciption: 'new publication by new user', userId: data.userId })

}
addCallback('user.create.async', insertPublicationAfterUserCreated);

 

Once a new user is created, this function insertPublicationAfterUserCreated is run. In 1 line, it inserts a new publication, using Publications.insert. Publication is imported in the second line from the collection.js file.