我正在使用meteor 1.2.1,以及在Sales集合中使用以下数据的数据库
{
"_id" : 1,
"table" : "Table no 2",
"name" : "Hot Coffee",
"quantity" : 2,
"price" : "$10",
"seller" : "User",
"createdAt" : ISODate("2016-01-06T12:57:17.152Z")
},
{
"_id" : 2,
"table" : "Table no 3A",
"name" : "Hot Coffee",
"quantity" : 1,
"price" : "$10",
"seller" : "User",
"createdAt" : ISODate("2016-02-01T12:58:17.152Z")
},
{
"_id" : 3,
"table" : "Table no 3A",
"name" : "Pizza",
"quantity" : 2,
"price" : "$50",
"seller" : "User",
"createdAt" : ISODate("2016-01-06T12:58:17.152Z")
},
{
"_id" : 4,
"table" : "2A",
"name" : "Pizza",
"quantity" : 5,
"price" : "$50",
"seller" : "User",
"createdAt" : ISODate("2016-02-02T11:55:17.152Z")
},
我在server / publication.js上有以下代码
Meteor.publish('getNewSales', function (opts) {
var initializing = 1;
function run(action) {
// Define the aggregation pipeline ( aggregate(pipeline) )
var pipeline = [
{
"$group": {
"_id": "$productName",
"quantity": { "$sum": "$quantity" }
}
},
{
"$project": {
"productName": "$_id", "_id": 0, "quantity": 1
}
}
];
Sales.aggregate(pipeline).forEach(function(e){
this[action]('distinct-sales', e.productName, e)
this.ready()
});
};
// Run the aggregation initially to add some data to your aggregation collection
run('added');
// Track any changes on the collection we are going to use for aggregation
var handle = Sales.find({}).observeChanges({
added(id) {
// observeChanges only returns after the initial `added` callbacks
// have run. Until then, we don't want to send a lot of
// `self.changed()` messages - hence tracking the
// `initializing` state.
if (initializing && initializing--) run('changed');
},
removed(id) {
run('changed');
},
changed(id) {
run('changed');
},
error(err) {
throw new Meteor.Error('Aaaaaaaaah! Grats! You broke it!', err.message)
}
});
// Stop observing the cursor when client unsubs.
// Stopping a subscription automatically takes
// care of sending the client any removed messages.
this.onStop(function () {
handle.stop();
});
});
现在我如何订阅聚合数据?
到目前为止我做了什么:
Tracker.autorun(function(){
var subscription = Meteor.subscribe('getNewSales');
if(subscription.ready()){
console.log(Sales.find({}));
}
)}