fetching and assigning value to childByAutoId from database

69 views Asked by At

I am trying to fetch a childByAutoId value from my database to set, but my child is returning nil.

My database looks like,

notifications
 -UID123
  -childByAutoID (this is what I am trying to set as jobPostId)
    -data 

jobPost 
  -UID123 
   -childByAutoID 
    -data

This image represents my notification structure Database Details

This is an issue because if the UID has two or more postings (jobPostId), each post's details will be saved inside of jobPostDetails.

So in this case, User Z3h4.. has two postings. If we trigger a notification for one posting, jobPostDetails for both jobPost are being saved under 1 notification for a specific post.

The method I am going with is I am trying locate the specific jobPost, grab its childByAutoID and then attach its details to the notification. Here is how I am trying to do so.

    private func postSwipeAndNotificationToDatabase(uid: String, values: [String: Any], jobPostId: String) {
let ref = Database.database().reference()

// Skipping directly to the jobPostId relevant part...
Database.database().reference().child("jobPost").child(uid).child(jobPostId).observeSingleEvent(of: .value) { snapshot in
    guard let jobPostData = snapshot.value as? [String: Any] else {
        print("Error: Failed to fetch job post details for ID: \(jobPostId)")
        return
    }
    
    var notificationValues = values
    notificationValues["jobPostId"] = jobPostId  // Include the jobPostId to link the notification directly to the job post.
    notificationValues["jobPostDetails"] = jobPostData  // Include job post details in notification data.

    let notificationRef = ref.child("notifications").child(uid)
    notificationRef.setValue(notificationValues) { error, _ in
        if let error = error {
            print("Failed to save notification: \(error.localizedDescription)")
            return
        }
        print("Successfully saved swipe and corresponding notification with job post details.")
    }
}
}

But the issue I am facing, is the jobPostId is returning nil.

Database.database().reference().child("jobPost").child(uid).child(jobPostId)

Any clues on how to fetch and set the jobPostId properly? This way, I can save jobPostDetails to the proper notification

0

There are 0 answers