Publish: Checks relating to Collection Setup Pre-Usage Per User [Solved]



Had a quick question around publishes. I have a module which rely’s on a collection, but this is not initialised anywhere specific. Hence, the idea is:

(1) In publication, do Collection.find({ _id: <…> })
(2) If empty, run a setupCollection() method. Populate the Collection with some stuff on a per user basis.
(3) Once this is done, publish the collection (now populated).
(4) Subscription picks up data and all is good.

Where should I put this check? Should it be in the publication or in the subscription. I use the container pattern so either is not a problem. Currently this is being handled in a componentWillMount() in the component downstream from the container itself. This seems not ‘the meteor way (whatever that means)’

The question is more around where this (once per user) check (and db setup of user specific entry in collection if required) should be. I’m already using the container model, so loads are fine on a regular basis.

Effectively like fixtures but for a specific collection, only if the user has been permission to it… Looking at this, maybe handle it at the publication, but this behaviour is not an error in the publication, so not sure.

Thanks so much.




So how I ended up solving this is do the check in the publication:

import { Meteor } from 'meteor/meteor';
import { Libs } from '../libs.js';

import { setupLibrary } from '../setupLibrary.js'; // module to do whatever setup...

Meteor.publish('libs.userCont', function() {
  if (!Libs.findOne({ libOwner: this.userId })) {

  return Libs.find({ libOwner: this.userId });

It seems to work fine, but not entirely convinced this is the best solution. Thanks so much.



I think that in principle that’s a pragmatic solution. You’ve followed the important part of using this.userId in the query, so it tracks user changes reactively.

The only point I would make is that in a multi-server scenario there is a small window of opportunity for more than one server process to execute the setupLibrary on behalf of the same user, but that is probably unlikely (the same user signed in on multiple clients at just the right time to hit the!Libs.findOne() test).

If you’re worried, you could make the setupLibrary idempotent as far as the db is concerned, or use an atomic interlock to ensure only one setupLibrary can be executed.


Thank you for the comment. Luckily this is not part of the use case currently. Hopefully will have this scaling problem in the future :slight_smile:

Not trying to blow smoke up your ass, but I’ve learnt something new every time you comment on a question. Guys like you are what make this forum. Thanks so much.



You’re very welcome :slight_smile:, but you should know that smoking’s bad for you :wink: