如
here所述,我想将Book对象存储在单独的ref中,并将其id值存储在User的books属性中
- 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的用户书籍数组中.
可以用一些漂亮的方式完成,而不是查询书籍,检索它的ID并将其添加到数组中吗?
也许我不应该使用AutoId模式并在应用程序中为自己创建每个对象的唯一ID?
解决方法
您可以通过以下方式获取childByAutoId创建的密钥:
- let newBookRef = self.ref!
- .child("Books")
- .childByAutoId()
- let newBookId = newBookRef.key
- let newBookData = [
- "book_id": newBookId,"title": arrayOfNames[0] as! NSString,"pages_count":arrayOfNames[2] as! NSString
- ]
- newBookRef.setValue(newBookData)