“arrayUnion”的 Firestore 规则更新给出权限被拒绝错误

问题描述 投票:0回答:1

在我的代码中,我通过添加一项来更新用户的“牌组”列表:

  const deckId = 'fake-deck-id';
  await updateDoc(doc(db, 'users', userId), {
    decks: arrayUnion(deckId),
  });

但是,这会产生

permission-denied
错误。这是我的 Firestore 规则:

  // Allow updates only to the "decks" and "votes" lists
  allow update: if request.auth != null &&
  request.auth.uid == userId &&
  (
  (
  // Allow updates to "decks" using array operations
  request.resource.data.keys().hasOnly(['decks']) &&
  request.resource.data.decks is list &&
  request.resource.data.decks.size() == resource.data.decks.size() + 1
  ) ||
  (
  // Allow updates to "votes" using array operations
  request.resource.data.keys().hasOnly(['votes']) &&
  request.resource.data.votes is list &&
  request.resource.data.votes.size() == resource.data.votes.size() + 1
  )
  );

我不明白为什么这不起作用。有人有什么想法吗?

firebase google-cloud-firestore firebase-security
1个回答
0
投票

您可以在

decks
中获得许可来解决此问题,如下所示:

  match /databases/{database}/documents {
    match /decks/{desk} {
      allow update: if request.resource.data.keys().hasOnly(['decks'])  // Only 'decks' field is updated
        && request.resource.data.decks is list  // 'decks' must be a list
        && request.resource.data.decks.size() == resource.data.decks.size() + 1;  // The size must be one more than the current list size
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.