Meteor update等操作失败原因及解决方法

Meteor 提供了两个 MongoDB 数据库:一个客户端缓存数据库和服务器上的一个 MongoDB 数据库。当一个用户更改一些数据时(例如通过单击 Save),在浏览器中运行的 JavaScript 代码会更新本地 MongoDB 中的相应的数据库项,然后向服务器发出一个 DDP 请求。该代码立即像操作已获得成功那样继续运行,因为它不需要等待服务器回复。与此同时,服务器在后台更新。如果服务器操作失败或返回一个意外结果,那么客户端 JavaScript 代码会依据从服务器新返回的数据立即进行调整。

昨天写代码的时候发现,发现有一个update操作总是失败,而也没有什么错误提示,只显示个error。找了很久找不到问题出在哪。

然后去读官方文档,它是这样写的:

文档中关于update的说明: collection.update(selector, modifier, [options], [callback]) Anywhere

Modify one or more documents in the collection

Arguments

selector Mongo selector, or object id

Specifies which documents to modify

modifier Mongo modifier

Specifies how to modify the documents

callback Function

Optional. If present, called with an error object as its argument.

Options

multi Boolean

True to modify all matching documents; false to only modify one of the matching documents (the default).

再查看一次我写的代码,应该没错的。然后再mongodb的命令行工具上试试执行同样语句也是可以的,于是我就觉得是Meteor的相关设置问题。

再往文档中细看,发现问题了:

The behavior of update differs depending on whether it is called by trusted or untrusted code. Trusted code includes server code and method code. Untrusted code includes client-side code such as event handlers and a browser’s JavaScript console.

Trusted code can modify multiple documents at once by setting multi to true, and can use an arbitrary Mongo selector to find the documents to modify. It bypasses any access control rules set up by allow and deny.

Untrusted code can only modify a single document at once, specified by its _id. The modification is allowed only after checking any applicable allow and deny rules.

原来为了安全性,Meteor限制了在客户端下默认的对数据库的操作,对insert,update,remove等操作的selector只能为 _id,并且不能使用mutil等,,所以我写的那条update语句的错误在于selector用了_id外的条件。所以看来解决方法有两个:

在客户端只是用_id作为selector的操作,显然这样不方便在服务器端写allow规则, 允许客户端直接对数据库进行这些操作

文档中关于allow的说明: collection.allow(options) Server

Allow users to write directly to this collection from client code, subject to limitations you define. Options

insert, update, remove Function

Functions that look at a proposed modification to the database and return true if it should be allowed.

于是写了相关的allow规则, 让他在某个情况下return true就可以了

感受最美的风景。你曾经说,

Meteor update等操作失败原因及解决方法

相关文章:

你感兴趣的文章:

标签云: