Got duplicated data when subscribe multiple times

爱⌒轻易说出口 提交于 2019-12-25 17:04:35

问题


I am using MongoDB aggregation in meteor. I got duplicated data when subscribe multiple times.

(The data in database are static, which means they are same all the time.)

// Server side

Meteor.publish('totalNumber', function () {
  let pipeline = [
    { $unwind: '$product' },
    { $group: {
      _id: {
        code: '$product.code',
        hour: { $hour: '$timestamp' }
      },
      total: { $sum: '$product.count' },
    }}
  ];

  Products.aggregate(
    pipeline,
    Meteor.bindEnvironment((err, result) => {
        console.log('result', result);  // at here every time subscribe, no duplicated data
        _.each(result, r => {
          this.added('totalNumber',
            // I use Random.id() here, because "Meteor does not currently support objects other than ObjectID as ids"
            Random.id(), {
              code: r._id.code,
              hour: r._id.hour,
              total: r.total
          });
        });
      }
    )
  );

  this.ready();
});

// Client side

this.subscribe('totalNumber', () => {
  // Correct result: [Object, Object] for example
  console.log(Products.find().fetch());
}, true);

this.subscribe('totalNumber', () => {
  // Wrong result: [Object, Object, Object, Object]
  console.log(Products.find().fetch());
}, true);

this.subscribe('totalNumber', () => {
  // Wrong result: [Object, Object, Object, Object, Object, Object]
  console.log(Products.find().fetch());
}, true);

So right now basically, the new results always include last time subscribe data.

How can I solve this problem? Thanks


回答1:


The problem is that you are using a random id each time in the call to added so the client always thinks all of the documents are unique. You need to devise a consistent id string generator. Using an answer to this question, you could imagine building a set of functions like these:

hashCode = function (s) {
  return s.split('').reduce(function (a, b) {
    a = ((a << 5) - a) + b.charCodeAt(0);return a & a;
  }, 0);
};

objectToHash = function (obj) {
  return String(hashCode(JSON.stringify(obj)));
};

So if you wanted a unique document for each combination of code and hour you could do this:

var id = objectToHash(r._id);
this.added('totalNumber', id, {...});


来源:https://stackoverflow.com/questions/36023747/got-duplicated-data-when-subscribe-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!