DCDC DCDC - 1 year ago 117
Swift Question

Firebase Swift - How to create a child and add its id to another ref property?

As described here, I'd like to store Book objects in a seperate ref and store its id value inside

property of

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]]

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 quering 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?

Answer Source

You can get the key created by childByAutoId in this way:

let newBookRef = self.ref!

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download