【问题标题】:I have a database, if I want to retrieve a field of a specific document I can, but I would like to retrieve a field from the last document updated我有一个数据库,如果我想检索特定文档的字段,我可以,但我想从最后更新的文档中检索一个字段
【发布时间】:2022-01-10 16:38:35
【问题描述】:

以这种方式工作,我去检索该文档的字段(在本例中为extranote),但是如果我只对按时间顺序插入的最后一个文档的该字段感兴趣怎么办?

我查找了类似的示例,但我不希望在创建数据库时仅添加一些我显然不知道的选项。

创建此模型是为了直接读入数据库而无需通过应用程序:

struct WorkoutModel: Identifiable,Codable {
    //var id = UUID().uuidString
    @DocumentID var id : String?
    var extranote : String
    var error: String = ""
}




struct SimpleEntry: TimelineEntry {
    let date: Date
    var deviceCount: Int
    var deviceMake: String
    var deviceModel: String
    var deviceType: String
    let configuration: ConfigurationIntent
    var workoutData: WorkoutModel?
}

func fetchFromDB(completion: @escaping (WorkoutModel)->()){
        let db = Firestore.firestore().collection("devices").document("lEp5impGTGeBmAEisQT")
        
        db.getDocument { snap, err in
            guard let doc = snap?.data() else {
                completion(WorkoutModel(extranote: "", error: err?.localizedDescription ?? ""))
                return
            }
            let extranote = doc["extranote"] as? String ?? ""
            completion(WorkoutModel(extranote: extranote))
        }
    }

func getTimeline(for configuration: ConfigurationIntent, in context: Context, 
   completion: @escaping (Timeline<Entry>) -> ()) {
        var entries: [SimpleEntry] = []
        
        // Generate a timeline consisting of five entries an hour apart, starting 
  from the current date.
        let date = Date()
        let nextUpdate = Calendar.current.date(byAdding: .minute, value: 5, to:date)!
        
    

fetchFromDB { work in
        let entry = SimpleEntry(date: nextUpdate, deviceCount: 
           deviceCount,deviceMake: deviceMake,deviceModel: deviceModel,deviceType: 
           deviceType, configuration: configuration, workoutData: work)
        entries.append(entry)
        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }
}

【问题讨论】:

    标签: swift firebase google-cloud-firestore


    【解决方案1】:

    如果您不知道要更新的文档的 ID,那么您需要 query the collection 获取该文档。如果您在该文档中没有指示其上次更新时间戳的字段,那么您将根本无法进行该查询。因此,您必须在文档中添加一个字段,并确保每次写入时都使用当前时间戳填充它。然后,如果您想稍后再次更新,可以使用该字段进行查询。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 2019-12-18
      • 2021-04-17
      • 1970-01-01
      相关资源
      最近更新 更多