[英]Meteor.js Publishing and Subscribing?
好的,所以我对Meteor.js的某些事情感到困惑。 我用它创建了一个网站来测试各种概念,它运行良好。 一旦我删除了“不安全”和“自动发布”,我在尝试检索并推送到服务器时会收到多个“拒绝访问”错误。 我相信它与以下代码段有关:
Template.posts.posts = function () {
return Posts.find({}, {sort: {time: -1}});
}
我认为它正在尝试直接访问该集合,允许它启用“不安全”和“自动发布”,但是一旦它们被禁用,它就会被拒绝访问。 我认为另一件作品存在问题:
else {
Posts.insert({
user: Meteor.user().profile.name,
post: post.value,
time: Date.now(),
});
我认为同样的事情正在发生:它试图直接访问集合,这是不允许的。
我的问题是,我如何重新考虑它,以便我不需要启用“不安全”和“自动发布”?
谢谢。
编辑
最后:
/**
* Models
*/
Posts = new Meteor.Collection('posts');
posts = Posts
if (Meteor.isClient) {
Meteor.subscribe('posts');
}
if (Meteor.isServer) {
Meteor.publish('posts', function() {
return posts.find({}, {time:-1, limit: 100});
});
posts.allow({
insert: function (document) {
return true;
},
update: function () {
return false;
},
remove: function () {
return false;
}
});
}
好的,这个问题有两个部分:
自动发布
要在meteor中发布数据库,您需要在项目的服务器端和客户端都有代码。 假设你已经实例化了该集合( Posts = new Meteor.Collection('posts')
),那么你需要
if (Meteor.isServer) {
Meteor.publish('posts', function(subsargs) {
//subsargs are args passed in the next section
return posts.find()
//or
return posts.find({}, {time:-1, limit: 5}) //etc
})
}
然后为客户
if (Meteor.isClient) {
Meteor.subscribe('posts', subsargs) //here is where you can pass arguments
}
不安全
不安全的目的是允许客户端不加选择地添加,修改和删除它想要的任何数据库条目。 但是,大多数时候你不希望这样。 删除不安全后,您需要在服务器上设置规则,详细说明谁可以执行哪些操作。 这两个函数是db.allow和db.deny。 例如
if (Meteor.isServer) {
posts.allow({
insert:function(userId, document) {
if (userId === "ABCDEFGHIJKLMNOP") { //e.g check if admin
return true;
}
return false;
},
update: function(userId,doc,fieldNames,modifier) {
if (fieldNames.length === 1 && fieldNames[0] === "post") { //they are only updating the post
return true;
}
return false;
},
remove: function(userId, doc) {
if (doc.user === userId) { //if the creator is trying to remove it
return true;
}
return false;
}
});
}
同样,db.deny的行为方式完全相同,但响应为true
意味着“不允许此操作”
希望这能回答你所有的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.