【发布时间】:2016-08-05 11:58:38
【问题描述】:
在预先添加的代码中的流星框架中,每次单击时计数器都会增加。如何使用 mongodb 保存值?
【问题讨论】:
标签: meteor
在预先添加的代码中的流星框架中,每次单击时计数器都会增加。如何使用 mongodb 保存值?
【问题讨论】:
标签: meteor
在服务器端创建一个集合来持久化数据:
Meteor.isServer {
Counter= new Mongo.Collection('Counter');
// Server side method to be called from client
Meteor.methods({
'updateCounter': function (id) {
if(typeof id && id) {
return Counter.update({_id: id}, {$set: {counter: {$inc: 1}}});
} else {
return Counter.insert({counter: 1})
}
}
})
// Publication
Meteor.publish("counter", function () {
Counter.find();
})
}
您可以在客户端订阅数据:
Meteor.isClient{
Template.yourTemplateName.created = function () {
Meteor.subscribe('counter');
}
Template.yourTemplateName.heplers( function () {
counter: function () {
return Counter.findOne();
}
})
Template.yourTemplateName.event( function () {
'click #counterButtonIdName': function () {
if(Counter.findOne()) {
Meteor.call('updateCounter', Counter.findOne()._id);
} else {
Meteor.call('updateCounter', null);
}
}
})
}
HTML 示例
<template name="yourTemplateName">
<span>{{counter}}</span> //area where count is written
</template>
通过这种方式,您可以实现对数据的安全服务器端处理,并且计数将保持不变,直到数据库中有数据为止。此外,您还可以通过这种方式学习 Meteor 的基础知识。
【讨论】:
只需insert 即可收藏。这是一个upsert(即,如果存在则更新,如果不存在则插入)函数:
if (Saves.find({_id: Meteor.userId()})){
Saves.update( {_id: Meteor.userId()}, {save: save} )
console.log("Updated saves")
}
else {
Saves.insert(save)
}
【讨论】:
如果autopublish 包存在,您可以简单地创建一个Mongo.Collection 并将这个计数器插入到数据库中:
var myCounter = 5;
var collection = new Mongo.Collection('collection');
collection.insert({counter: myCounter});
希望这会有所帮助。
【讨论】: