gpt4 book ai didi

javascript - Meteor - 如何更新数组中的文档

转载 作者:行者123 更新时间:2023-11-27 23:36:27 25 4
gpt4 key购买 nike

我的数组中有一个文档,并尝试更新文档中的值。

它已经可以在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com