0

这是用于计数事物的 Meteor 应用程序的一些代码(带有相关数据)的本质。计数可以链接在一起,以便一个可以增加另一个:

// The counting and linking code.
Meteor.methods({
    'counts.increment'(countId) {
        const count = Counts.findOne(countId);
        Counts.update(countId,{ $inc: { count: 1 } })
        Meteor.call('counts.check-links',count._id);
    },
    'counts.check-links'(countId){
        var count = Counts.findOne(countId);
        count.links.forEach(function (linkId) {
            updated = false;
            const link = Links.findOne(linkId);
            const primary = Counts.findOne(link.primary);
            const secondary = Counts.findOne(link.secondary);
            if (primary.count == link.level) {
                updated = true;
                Counts.update(secondary._id, {$inc: {count: 1}});
            }
            if (updated) {
                Meteor.call('counts.check-links',secondary._id);
            }
        })
    }
})

// Some data...
Count: {
  _id: 1,
  value: 0,
  name: A,
  links: [3]
}

Count: {
  _id: 2,
  value: 0,
  name: B,
  links: [4]
}

Link: {
  _id: 3,
  primary: 1,
  secondary: 2
}

Link: {
  _id: 4,
  primary: 2,
  secondary: 1
}

因此,如果Meteor.call('projects.increment',1)调用此代码,则会因为每个计数都链接到另一个计数而崩溃。检测这样的设置可能相当困难,因为可能存在非常复杂的计数安排,并且链接也可能减少,设置为零,每 N 个计数操作一次等等。&C。不过,出于提出这个问题的目的,这并不重要。

我想到的一种可能性是添加一个计数器counts.check-links,在任意循环次数(例如 5 次)后将在该计数器内停止执行。据推测,为了防止篡改该计数器的值,必须将其存储在数据库中并通过流星法。它需要在任何check-links调用序列结束时重置。

我不确定这是否是最好的主意,或者如果是这样,如何实现它的好方法,所以我很想知道是否有人有任何建议。

4

1 回答 1

1

您可以创建一组已访问过的所有对象(“计数”);因此,如果您点击指向此类对象的链接,则可以避免再次处理它,从而陷入无限递归。

编辑:示例我不熟悉流星,所以如果它不能按预期工作,请原谅......不过,这是所有允许对象引用指针的编程语言的常见问题,并且解决方案遵循类似的图案。

// The counting and linking code.
Meteor.methods({
  ...
'counts.check-links'(countId, alreadyVisited){

    if (!alreadyVisited) alreadyVisited = {};
    if (alreadyVisited[countId]) return;
    alreadyVisited[countId] = true;

    var count = Counts.findOne(countId);
    count.links.forEach(function (linkId) {
        updated = false;
        const link = Links.findOne(linkId);
        const primary = Counts.findOne(link.primary);
        const secondary = Counts.findOne(link.secondary);
        if (primary.count == link.level) {
            updated = true;
            Counts.update(secondary._id, {$inc: {count: 1}});
        }
        if (updated) {
            Meteor.call('counts.check-links',secondary._id, alreadyVisited);
        }
    })
}
于 2017-04-24T10:04:24.557 回答