Как реактивно агрегировать mongodb в метеоре

Я новичок в метеоре. Я разработал концепцию публикации / подписки. Я сталкиваюсь со следующей ошибкой при выполнении агрегации реактивно.

код клиента:

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import './main.html';

Template.header.helpers({
    'tasks': function () {
        console.log("tasks helper called : ");     

        Meteor.subscribe('reportTotals', function() {
            console.log(clientReport.find().fetch());
        });

        return ['1', '2'];
    },   
});

код сервера

import { Meteor } from 'meteor/meteor';
import {ReactiveAggregate} from 'meteor/jcbernack:reactive-aggregate';

Meteor.startup(() => {
    console.log("Server Started");
  // code to run on server at startup
  var MONGO_URL = "mongodb://127.0.0.1:27017/test";  
});

Meteor.publish("reportTotals", function() {
// Remember, ReactiveAggregate doesn't return anything
this.autorun(function () {
ReactiveAggregate(this, atm_data, [{
    // assuming our Reports collection have the fields: hours, books    
    $group: {
        '_id': null,
        'bottles_used': {
        // In this case, we're running summation. 
            $sum: '$BOTTLE_USED'
            // $sum: 1
        }
    }
}, {
    $project: {
        // an id can be added here, but when omitted, 
        // it is created automatically on the fly for you
        bottles_used: '$bottles_used'
    } // Send the aggregation to the 'clientReport' collection available for client use
}], { clientCollection: "clientReport" });    
    });
});   

Исключение при очистке буферизованных записей DDP: Ошибка: ожидается, что документ будет изменен в Object.update ( http://localhost:3000/packages/mongo.js?hash=ed0b13aca2f180af120dd0cfdba64ac79e2a624f:246:29)... Заранее спасибо.

2 ответа

У вас нет коллекции на стороне клиента. Кроме того, вам нужно подписаться, прежде чем позвонить этому помощнику.

Попробуй это

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import './main.html';

var clientReport = new Mongo.Collection('clientReport');

Meteor.subscribe("reportTotals");

Template.header.helpers({
    'tasks': function () {
        console.log("tasks helper called : ");     
        console.log(clientReport.find().fetch());
    },   
});

Вам также не нужен конвейер и автозапуск кода сервера, попробуйте это:

AtmData = new Mongo.Collection('atmdata');

Meteor.startup(() => {
  // code to run on server at startup
/*     AtmData.insert({
        bottles_used: 123,
    }); */

});



Meteor.publish("reportTotals", function() {
// Remember, ReactiveAggregate doesn't return anything

    ReactiveAggregate(this, AtmData, [{
        // assuming our Reports collection have the fields: hours, books    
        $group: {
            '_id': null,
            'bottles_used': {
            // In this case, we're running summation. 
                $sum: '$bottles_used'
                // $sum: 1
            }
        }
        }], { clientCollection: "clientReport" });    
});

Я сделал пакет NPM здесь: meteor-publish-join. Его основная цель - публиковать дорогостоящие агрегированные значения через определенный промежуток времени. Надеюсь, это поможет в вашем случае.

Другие вопросы по тегам