Firebase,多位置更新

Firebase,多位置更新,firebase,atomic,firebase-security,Firebase,Atomic,Firebase Security,考虑以下代码,用于FireBase中多个位置的原子写入: var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com"); var newPostRef = ref.child("posts").push(); var newPostKey = newPostRef.key(); var updatedUserData = {}; updatedUserData["users/"+authData.uid+

考虑以下代码,用于FireBase中多个位置的原子写入:

var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");

var newPostRef = ref.child("posts").push();
var newPostKey = newPostRef.key();

var updatedUserData = {};
updatedUserData["users/"+authData.uid+"/posts/" + newPostKey] = true;
updatedUserData["posts/" + newPostKey] = {
  title: "New Post",
  content: "Here is my new post!"
};

ref.update(updatedUserData, function(error) {
  if (error) {
    console.log("Error updating data:", error);
  }
});
var ref=新Firebase(“https://.firebaseio.com");
var newPostRef=ref.child(“posts”).push();
var newPostKey=newPostRef.key();
var updateUserData={};
UpdateUserData[“users/”+authData.uid+“/posts/”+newPostKey]=true;
UpdateUserData[“posts/”+newPostKey]={
标题:“新职位”,
内容:“这是我的新帖子!”
};
ref.update(updatedUserData,函数(错误){
如果(错误){
日志(“更新数据时出错:”,错误);
}
});
这种方法可以用于在不同的位置更新帖子,但是如何在服务器端强制执行原子更新呢?(通过规则)


如何确保用户在不填充
用户/UID/posts/
的情况下无法更新位置
/posts/
(通过其直接引用),或者反之亦然?

有许多可能的“业务规则”,因此我将选择一个并实现它。假设用户引用的任何帖子都必须存在。因此,如果存在
/posts/mypostid
,则只能向
/users/myuid/posts/mypostid
写入。我还将实现帖子本身的基本验证

{
  "posts": {
    "$postid": {
      ".validate": "hasChildren(['title', 'content'])",
      "title": {
        ".validate": "newData.isString()"
      },
      "content": {
        ".validate": "newData.isString()"
      },
      "$other": {
        ".validate": false
      }
    }
  },
  "users": {
    "$uid": {
      "posts": {
        "$postid": {
          ".validate": "newData.parent().parent().parent().parent().child('posts').child($postid).exists()
        }
      }
    }
  }
}
这里最大的技巧是
newData.parent().parent()…
位,它确保我们在新数据中获得帖子


你有一个习惯,比如问“我怎样才能确保ABC方法被用于更新数据?”,这很少是思考问题的正确方式。在上面的规则中,我专注于验证数据的结构,并不关心什么API调用可能会导致该数据。

谢谢Frank,我使用了类似的方法,但我把自己弄糊涂了,因为使用了newData.val()而不是
exists()
。。顺便说一句,我刚刚添加了“更新源”部分,以便向读者清楚地表明,我正在寻找一个服务器端解决方案,以确保正确的输出,无论客户端发生了什么。。。但无论如何,谢谢你的回答。解决了我的问题:)如果你已经有了一个不起作用的方法,那么一定要把你的问题贴出来。它表明您已经尝试了一些内容,并且允许我们将代码片段复制/粘贴到答案中。关于此问题,可以
newData.parent()…
”中多次使用。验证“
特定节点的规则?”?