这是一个老问题,但我希望我的回答可以帮助像我一样需要此信息的其他人。
我有时需要一些杂项但反应性的数据来在 UI 中显示指标,文档计数就是一个很好的例子。
- 创建一个不会在服务器上导入的可重用(导出)客户端集合(以避免创建不必要的数据库集合)。请注意作为参数传递的名称(此处为“misc”)。
import { Mongo } from "meteor/mongo";
const Misc = new Mongo.Collection("misc");
export default Misc;
- 在接受
docId 和将保存计数的key 的名称的服务器上创建一个发布(使用默认值)。要发布到的集合名称
是用于创建仅客户端集合(“misc”)的集合。 docId 值无关紧要,它只需要在所有 Misc 文档中是唯一的,以避免冲突。有关发布行为的详细信息,请参阅 Meteor docs。
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();
});
});
- 在客户端,导入集合,确定
docId 字符串(可以保存在常量中),订阅发布并获取适当的文档。瞧!
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 };
});