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

11,920

Solution 1

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)

Solution 2

To retrieve newly created autoId :-

let refer = self.ref!.child("Books").childByAutoId()
    let createdId = refer.key   //Your autoID
    refer.setValue(["title": arrayOfNames[0] as! NSString, "author": arrayOfNames[1] as! NSString , "pages_count":arrayOfNames[2] as! NSString])

A even better way would be to replace autoId to timeStamp for future reference for as to when was the book added:-

  let timestamp = Int(NSDate.timeIntervalSinceReferenceDate*1000)  //Unique 
  self.ref!.child(timeStamp).setValue(["title": arrayOfNames[0] as! NSString, "author": arrayOfNames[1] as! NSString , "pages_count":arrayOfNames[2] as! NSString])
Share:
11,920
theDC
Author by

theDC

iOS dev and cofounder at codepany.com

Updated on July 29, 2022

Comments

  • theDC
    theDC almost 2 years

    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?