Reputation: 6357
I am having trouble inserting a new record into a Firebase database. Though I am able to add a new record, all of my previous data is being overwritten.
In Firebase I have this simple data model:
{
"appName": {
"devices": {
"CBB60958-3D6E-4F42-96AE-6345471B1F38": {
"lat": 37.39747477,
"lon": -122.17969227,
"updated": 1493312965,
"username": "username"
}
}
}
}
The guid represents the device ID. If a new device is loaded, I want to add a new record to the 'tracking' section in the same format. I have the following update function:
fileprivate func initializeDevice() {
if !deviceExists {
let post = [self.guid: [
"lat" : locationManager.location?.coordinate.latitude ?? 0.0,
"lon" : locationManager.location?.coordinate.longitude ?? 0.0,
"updated" : Int(Date().timeIntervalSince1970),
"username" : username ]]
dbRef.child("devices").setValue(post)
}
}
I've been testing about every method available in the database reference and though I am able to insert a record, all of my previous device records are deleted, leaving only the current record. So it seems that my code is updating all of the data in the devices section rather than appending a new record to it.
Can anyone point me in the right direction to simply insert a new record? Thanks!
Upvotes: 1
Views: 2532
Reputation: 4507
That's the whole point. When you insert an object, the whole earlier object gets overwritten.
For example, if you have an object at a path uid.messages.messageid
and you save to said messageid
, the whole object will get overwritten. Thus, you basically need to have the old object, make changes to it, and save it back.
In your case, you use the code dbRef.child("devices").setValue(post)
. You are setting the value of that path to whatever post is.
To create a new child to a reference, here is what you normally would do. First, use the childByAutoId
method to get a new unique ID which you can then access in the same by let key = childByAutoId().key
. And then save your new object to the reference with reference.key
.
If you haven't already done it, take a look at the tutorials/guides at Firebase docs. They have some good advice on data structures you should be using (i.e. making flat structures instead of nested ones), and how you would be accessing and updating things to be efficient.
Finally, here's the documentation that would tell you the same answer: https://firebase.google.com/docs/database/ios/read-and-write.
Upvotes: 3