As described here, I'd like to store Book objects in a separate ref and store its id value inside books
property of User
Users:
user_id:121jhg12h12
email: "[email protected]"
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
Whenever I add a book inside the app
self.ref!.child("Books").childByAutoId().setValue(["title": arrayOfNames[0] as! NSString, "author": arrayOfNames[1] as! NSString , "pages_count":arrayOfNames[2] as! NSString])
The book object is created in Books ref, but I'd like to add its id to the User's books array of user right away.
Can it be done in some nifty way, instead of querying the book, retrieve its ID and add it to the array?
If no, what's the proper way o querying the object id that has been just created?
Maybe I should not use AutoId mode and create unique Id for each object by myself in app?
You can get the key created by childByAutoId in this way:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With