Firestore - Subcollections Swift

时间:2018-05-03 21:17:00

标签: swift firebase collections google-cloud-firestore

所以我正在尝试学习一些Firestore基本功能,并在YouTube上观看了“Kilo Locos”视频,解释了CRUD操作。我想采用他的代码方法并从中创建子集合。基本上,我如何添加集合并使“用户”集合成为此新集合的子集合。非常感谢任何帮助,非常感谢!!

以下是下载项目的链接: https://kiloloco.com/courses/youtube/lectures/3944217

FireStore服务

import Foundation
import Firebase
import FirebaseFirestore

class FIRFirestoreService {

private init() {}
static let shared = FIRFirestoreService()

func configure() {
    FirebaseApp.configure()
}

private func reference(to collectionReference: FIRCollectionReference) -> CollectionReference {
    return Firestore.firestore().collection(collectionReference.rawValue)
}

func create<T: Encodable>(for encodableObject: T, in collectionReference: FIRCollectionReference) {
    do {
        let json = try encodableObject.toJson(excluding: ["id"])
        reference(to: collectionReference).addDocument(data: json)

    } catch {
        print(error)
    }
}

func read<T: Decodable>(from collectionReference: FIRCollectionReference, returning objectType: T.Type, completion: @escaping ([T]) -> Void) {

    reference(to: collectionReference).addSnapshotListener { (snapshot, _) in

        guard let snapshot = snapshot else { return }

        do {

            var objects = [T]()
            for document in snapshot.documents {
                let object = try document.decode(as: objectType.self)
                objects.append(object)
            }

            completion(objects)

        } catch {
            print(error)
        }
    }
}

func update<T: Encodable & Identifiable>(for encodableObject: T, in collectionReference: FIRCollectionReference) {

    do {

        let json = try encodableObject.toJson(excluding: ["id"])
        guard let id = encodableObject.id else { throw MyError.encodingError }
        reference(to: collectionReference).document(id).setData(json)

    } catch {
        print(error)
    }
}

func delete<T: Identifiable>(_ identifiableObject: T, in collectionReference: FIRCollectionReference) {

    do {

        guard let id = identifiableObject.id else { throw MyError.encodingError }
        reference(to: collectionReference).document(id).delete()

    } catch {
        print(error)
    }
}

}

FIRCollectionReference

import Foundation

enum FIRCollectionReference: String {

    case users

}

用户

import Foundation

protocol Identifiable {
var id: String? { get set }

}

struct User: Codable, Identifiable {
var id: String? = nil
let name: String
let details: String

init(name: String, details: String) {
    self.name = name
    self.details = details
}

}

可编码扩展程序

import Foundation

enum MyError: Error {
case encodingError

}

extension Encodable {

func toJson(excluding keys: [String] = [String]()) throws -> [String: Any] {

    let objectData = try JSONEncoder().encode(self)
    let jsonObject = try JSONSerialization.jsonObject(with: objectData, options: [])
    guard var json = jsonObject as? [String: Any] else { throw MyError.encodingError }

    for key in keys {
        json[key] = nil
    }

    return json

}

}

快照扩展程序

import Foundation
import FirebaseFirestore

extension DocumentSnapshot {

func decode<T: Decodable>(as objectType: T.Type, includingId: Bool = true) throws  -> T {

    var documentJson = data()
    if includingId {
        documentJson!["id"] = documentID
    }

    let documentData = try JSONSerialization.data(withJSONObject: documentJson!, options: [])
    let decodedObject = try JSONDecoder().decode(objectType, from: documentData)

    return decodedObject
}

}

1 个答案:

答案 0 :(得分:0)

Firestore结构不能将集合作为其他集合的子集。

您的问题的答案(如何添加集合并使用这个新集合中的&#39; User&#39;集合成为子集合?)是不可以的。相反,您必须在这两个集合之间放置一个文档。

Read this for more information.

它说:Notice the alternating pattern of collections and documents. Your collections and documents must always follow this pattern. You cannot reference a collection in a collection or a document in a document.