簡體   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