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

As described here , I would like to save the Book objects in a separate ref and keep its id value inside the books User property

 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 

Whenever I add a book inside the application

 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 the ref book, but I would like to immediately add its identifier to the user array of users.

Could this be done in some elegant way, instead of requesting a book, getting its identifier and adding it to the array?

If not, how can I request the identifier of the object that was just created?

Perhaps I should not use AutoId mode and create a unique identifier for each object on my own in the application?

+6
source share
2 answers

You can get the key generated by childByAutoId as follows:

 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) 
+13
source

To get the 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]) 

An even better way is to replace autoId with timeStamp for future use when a book has been 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]) 
+3
source

All Articles