You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firebase中按值更新单个文档实例?Swift标签更新疑问

How to Update a Single Tag Document by Title in Firebase (Swift)

Got it, let's fix your function so it can find each tag by its title and update it correctly. Here's how to adjust your code:

static func updateTags(tags: Array<String>) {
    guard let currentUser = User.current else {
        // Handle case where user isn't logged in
        return
    }
    let userTagsRef = Database.database().reference().child("tags").child(currentUser.uid)
    
    for tagTitle in tags {
        // Query to find the tag with the matching title
        userTagsRef.queryOrdered(byChild: "title")
                   .queryEqual(toValue: tagTitle)
                   .observeSingleEvent(of: .value) { snapshot in
            guard snapshot.exists() else {
                // Optional: Handle if the tag doesn't exist (e.g., create it or log an error)
                print("Tag \(tagTitle) not found for user \(currentUser.uid)")
                return
            }
            
            // Loop through matching results (should be one if titles are unique)
            for childSnapshot in snapshot.children {
                if let tagSnapshot = childSnapshot as? DataSnapshot {
                    let tagId = tagSnapshot.key // This is the tag's ID key you need
                    let targetTagRef = userTagsRef.child(tagId)
                    
                    // Create your updated tag object
                    let updatedTag = Tag(title: tagTitle, latestThumbnailURL: somethingnew, latestUpdate: now)
                    // Update the specific tag node
                    targetTagRef.updateChildValues(updatedTag.dictValue)
                }
            }
        }
    }
}

Key Details to Note:

  1. Query for Matching Titles: We use queryOrdered(byChild: "title") and queryEqual(toValue: tagTitle) to find all tags under the user's node that have the exact title we're looking for.
  2. Get the Tag ID: The key property of the DataSnapshot gives us the unique tag ID that Firebase generated (or you set) for that tag. This replaces your ????? placeholder.
  3. Single Event Observation: Using observeSingleEvent(of: .value) ensures we only fetch the data once, which is perfect for a one-time update operation.
  4. Indexing is Critical: For this query to work efficiently (especially as your dataset grows), you need to add an index in your Firebase Realtime Database rules. Add this to your database.rules.json:
    {
      "rules": {
        "tags": {
          "$uid": {
            ".indexOn": "title"
          }
        }
      }
    }
    
    This tells Firebase to index the title field under each user's tags, making the query fast even with many tags.
  5. Unique Titles: If you allow duplicate tag titles for a user, this code will update all matching tags. If you want to enforce unique titles, add logic to check for existing tags before creating new ones.

Optional: Handle Non-Existent Tags

If you want to create the tag if it doesn't exist instead of just skipping it, you can modify the guard block to call a create function. But based on your question, it sounds like you're only updating existing tags.

内容的提问来源于stack exchange,提问作者BigBoy1337

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:55:30