- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的数组中有一个文档,并尝试更新文档中的值。
它已经可以在 Meteor 的 Mongo shell 中运行了:
$ meteor mongo
meteor:PRIMARY> db.mycollection.update({name:"test", "foo.name":"bar"}, {$set: {"foo.$.price":42}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
但是当我尝试在 Meteor 中使用以下方法时,它不起作用:
MyCollection.update(
{name:"test", "foo.name":"bar"},
{$set: {"foo.$.price":42}}
);
正如您在这里看到的:http://meteorpad.com/pad/jjazD3jYYeY7R9Bpv/DocumentArrayUpdate
这是因为您无法在客户端放置与 ID 不同的选择器(使用自动发布/不安全):
Error: Not permitted. Untrusted code may only update documents by ID. [403]
这就是我迷路的地方。我必须在服务器上运行此更新代码,但到目前为止我见过的唯一示例只是在服务器上执行一些 .find()
或 .findOne()
Meteor.publish()
然后所有更新逻辑都在 Meteor.methods()
中完成,这是客户端和服务器端,所以在我的情况下我不能这样做。
我怎样才能做到这一点?
编辑:我说得有点快:Meteor.methods()
既是客户端又是服务器端,所以就我而言我不能这样做。。它实际上与 Meteor.methods()
配合得很好,我仍然不知道为什么,我认为它来自 Meteor 的 Optimistic UI 功能的工作原理......
最佳答案
Error: Not permitted. Untrusted code may only update documents by ID. [403]
这意味着您已经删除了不安全的软件包,这对于生产来说是一件好事。但这意味着您无法再从客户端更新数据库条目,除非您通过集合的 ID 进行更新(如错误所述。
所以你有两个选择。
首先 - 糟糕的选择。来自客户:
MyCollection.update(
{_id:"19283yhakjsdo23", "foo.name":"bar"},
{$set: {"foo.$.price":42}}
);
这不是很糟糕,但也不是很好。
好的选择:从服务器。
Meteor 有一种叫做服务器端方法的东西 (a good blog post about this is available) 。服务器端方法很棒,可以让您使用几乎完全相同的代码(但来自服务器)准确地执行您想要执行的操作。
因此,在 server
目录中名为 methods.js
的文件中,您可以编写:
Meteor.methods({
priceUpdateMethod(name, collectionkey, updateValue) {
MyCollection.update(
{name:name, "foo.name":"bar"},
{$set: {collectionkey: updateValue}}
);
}
});
然后在您的客户端目录中,您将有一个助手或类似的函数:
Meteor.call('priceUpdateMethod',"test","foo.$.price",42)
关于javascript - Meteor - 如何更新数组中的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34097391/
我是一名优秀的程序员,十分优秀!