Mongo集合未在客户端上更新

时间:2016-09-17 00:18:17

标签: javascript node.js meteor

我正在学习如何使用meteor,而我无法将客户端集合与服务器的内容同步。我试图通过调用服务器上的方法,每次单击它时使计数器增加1。当我去我的应用程序时,它总是显示1,但是当我通过Mongo shell对我的集合执行.find()时,它具有该数字实际应该是什么。我有自动发布,所以不应该自动生效吗?这是我的客户端和服务器代码:

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

import './main.html';
Counter= new Mongo.Collection('counter');
Template.counter.helpers({
  counter() {
    return Counter.find({});}
});

Template.counter.events({
  'click #a':function() {
      Meteor.call('add')

  },
});

/client/main.html
<head>
  <title>HypeCoins</title>
</head>

<body>
  <h1>HypeCoins</h1>

  {{> counter}}
</body>

<template name="counter">
  <button id='a'>Click Me</button>
  <p>You've pressed the button {{counter.count}} times.</p>
</template>



/server/main.js
import { Meteor } from 'meteor/meteor';
Counter= new Mongo.Collection('counter');

Meteor.startup(() => {

});
Meteor.methods({
    'add':function(){
        Counter.update({},{$inc:{count:1}});


    }

});

2 个答案:

答案 0 :(得分:0)

您必须定义集合架构。看看它应该对您有用的包:https://github.com/aldeed/meteor-simple-schema

答案 1 :(得分:0)

您将通过在更新中使用修饰符来获得解决方案。这将要求您创建一个ID,以便更新。你可以这样做:

的客户机/ main.js

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

import './main.html';

Counter = new Mongo.Collection('counter');

Template.counter.helpers({
  counter() {
    return Counter.findOne();
  }
});

Template.counter.events({
  'click #a':function() {
    Meteor.call('add');
  },
});

服务器/ main.js

import { Meteor } from 'meteor/meteor';

Counter = new Mongo.Collection('counter');

Meteor.methods({
    'add': function() {
      currentCount = Counter.findOne();

      if (!currentCount) {
        Counter.insert({ count: 1});
      }

      Counter.update({_id: currentCount._id }, { $inc: { count: 1 } });
    },
});

请参阅Meteor文档: https://docs.meteor.com/api/collections.html#Mongo-Collection-update

相关问题