Home > database >  How to create array of objects in firebase
How to create array of objects in firebase

Time:05-09

I am working on a project developing a car rental app. The app can be accessed by admin and user both with different roles. So at the moment i'm saving the car added by the admin using api / manually in firebase

     let vehicle = Vehicle(make: make, model: modell, price: price, mileage: mileage)
     db.collection("Admin").document("car").setData(from: vehicle) 

where vehicle is an object with properties like make model mileage ect. Now with this funtionality i always save one object. If i add a new object it overwrites it how can i store a multiple objects in car document.

enter image description here

CodePudding user response:

The reason why it is "updating" instead of "adding" when you are running above statements for second time because you are using the same DocumentID, which you specify as "car".

If you are running a for-loop function to add multiple vehicle documents, you can modify your codes similar to below example.

Method 1

let vehicleDocID: Int = 0

let vehicle = Vehicle(make: make, model: modell, price: price, mileage: mileage)

for vehicle in vehicleS {
     vehicleDocID  = 1
     db.collection("Admin").document("\(vehicleDocID)").setData(from: vehicle) 

}

Alternatively, you can simply use .add() function to get defaultID, which I personally recommend.

Method 2

var ref: DocumentReference? = nil
ref = db.collection("Admin").addDocument(data: [
    "make": "make",
    "model": "modell",
    "price": "price",
    "mileage": "mileage"
]) { err in
    if let err = err {
        print("Error adding document: \(err)")
    } else {
        print("Document added with ID: \(ref!.documentID)")
    }
}

enter image description here

Lastly, in case, if the number of vehicles are large (>100), I suggest you use batch writes to add the documents to Firestore, as it ensures better performance. For batch writes, you may refer to below Firestore documentation.

https://firebase.google.com/docs/firestore/manage-data/transactions

  • Related