[英]Mongo collection not updating on client
I'm learning how to use meteor and I'm having trouble syncing the clients collection with what the server has. 我正在学习如何使用流星,并且无法将客户端集合与服务器上的内容同步。 I'm trying to make a counter that increments by one every time you click it by calling a method on the server. 我试图通过每次调用服务器上的方法来使计数器增加一。 When I go to my application it always displays 1 but when I do .find() on my collection through the Mongo shell it has what the number should actually be. 当我进入我的应用程序时,它始终显示1,但是当我通过Mongo shell在集合上执行.find()时,它实际上应该是数字。 I have autopublish on so shouldn't this work automatically? 我已经自动发布了,所以这不应该自动工作吗? Here is my code for both client and server: 这是我的客户端和服务器代码:
/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}});
}
});
You have to define your collection schema. 您必须定义您的收集模式。 Take a look at that package it should be useful for you: https://github.com/aldeed/meteor-simple-schema 看一下该软件包,它对您应该有用: https : //github.com/aldeed/meteor-simple-schema
You will get your solution by using a modifier on your update. 您将通过在更新中使用修饰符来获得解决方案。 This will require you to create an ID so there is something to update. 这将需要您创建一个ID,以便进行更新。 You can do so by: 您可以通过以下方式进行操作:
client/main.js 客户端/ 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');
},
});
server/main.js 服务器/ 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 } });
},
});
Refer to Meteor documentation: https://docs.meteor.com/api/collections.html#Mongo-Collection-update 请参阅流星文档: https : //docs.meteor.com/api/collections.html#Mongo-Collection-update
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.