如here所述,我想将Book对象存储在单独的ref中,并将其id值存储在books
的User
属性内
Users:
user_id:121jhg12h12
email: "john@doe.com"
name: "John Doe"
profile_pic_path: "https://...".
language: "en"
exp_points: 1284
friends: [user_id]
books: [[book_id, status, current_page, start_date, finish_date]]
badges: [[badge_id, get_date]]
Books:
book_id: 3213jhg21
title: "For whom the bell tolls"
author: "Ernest Hemingway"
language: "en"
pages_count: 690
ISBN: "21hjg1"
year: 2007
每当我在应用程序中添加一本书时
self.ref!.child("Books").childByAutoId().setValue(["title": arrayOfNames[0] as! NSString, "author": arrayOfNames[1] as! NSString , "pages_count":arrayOfNames[2] as! NSString])
book对象是在Books ref中创建的,但是我想立即将其id添加到用户的User's books数组中。
是否可以通过一些漂亮的方法来完成,而不是查询书,而是检索书的ID并将其添加到数组中?
如果不是,查询刚刚创建的对象ID的正确方法是什么?
也许我不应该使用AutoId模式并由我自己在应用程序中为每个对象创建唯一的ID?
最佳答案
您可以通过以下方式获取childByAutoId创建的 key :
let newBookRef = self.ref!
.child("Books")
.childByAutoId()
let newBookId = newBookRef.key
let newBookData = [
"book_id": newBookId,
"title": arrayOfNames[0] as! NSString,
"author": arrayOfNames[1] as! NSString,
"pages_count":arrayOfNames[2] as! NSString
]
newBookRef.setValue(newBookData)