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