繁体   English   中英

Mongo集合未在客户端上更新

[英]Mongo collection not updating on client

我正在学习如何使用流星,并且无法将客户端集合与服务器上的内容同步。 我试图通过每次调用服务器上的方法来使计数器增加一。 当我进入我的应用程序时,它始终显示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}});


    }

});

您必须定义您的收集模式。 看一下该软件包,它对您应该有用: https : //github.com/aldeed/meteor-simple-schema

您将通过在更新中使用修饰符来获得解决方案。 这将需要您创建一个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 } });
    },
});

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM