This is an old question, but I hope my answer might help others who need this info as I did.
I sometimes need some miscellaneous but reactive data to display indicators in the UI and documents count is a good example.
- Create a reusable (exported) client-side only collection that won't be imported on the server (to avoid creating unnecessary database collection). Note the name passed as argument ("misc" here).
import { Mongo } from "meteor/mongo";
const Misc = new Mongo.Collection("misc");
export default Misc;
- Create a publication on the server that accepts
docId
and the name of the key
where the count will be saved (with a default value). The collection name to publish to
is the one used to create the client only collection ("misc"). The docId
value does not matter much, it just needs to be unique among all Misc docs to avoid conflicts. See Meteor docs for details about the publication behavior.
import { Meteor } from "meteor/meteor";
import { check } from "meteor/check";
import { Shifts } from "../../collections";
const COLL_NAME = "misc";
/* Publish the number of shifts that need revision in a 'misc' collection
* to a document specified as `docId` and optionally to a specified `key`. */
Meteor.publish("shiftsToReviseCount", function({ docId, key = "count" }) {
check(docId, String);
check(key, String);
let initialized = false;
let count = 0;
const observer = Shifts.find(
{ needsRevision: true },
{ fields: { _id: 1 } }
).observeChanges({
added: () => {
count += 1;
if (initialized) {
this.changed(COLL_NAME, docId, { [key]: count });
}
},
removed: () => {
count -= 1;
this.changed(COLL_NAME, docId, { [key]: count });
},
});
if (!initialized) {
this.added(COLL_NAME, docId, { [key]: count });
initialized = true;
}
this.ready();
this.onStop(() => {
observer.stop();
});
});
- On the client, import the collection, decide of a
docId
string (can be saved in a constant), subscribe to the publication and fetch the appropriate document. Voilà!
import { Meteor } from "meteor/meteor";
import { withTracker } from "meteor/react-meteor-data";
import Misc from "/collections/client/Misc";
const REVISION_COUNT_ID = "REVISION_COUNT_ID";
export default withTracker(() => {
Meteor.subscribe("shiftsToReviseCount", {
docId: REVISION_COUNT_ID,
}).ready();
const { count } = Misc.findOne(REVISION_COUNT_ID) || {};
return { count };
});
Tasks
belong to users or anything ? Why i am asking is that you can maintain that count insideusers
collection iteself and get it from there – Territerrible