Reputation: 13
I'am new on angular and Firebase and I don't understand something. i want to push url picture with unique key in my database. Now i have an array of url and I send it to my database like that:
and instead of 0,1,2 I want to push a unique ID
my code for push the data:
export class SpotsService {
spotsRef: AngularFireList<any>;
spotRef: AngularFireObject<any>;
spotiD: string;
picsUrl: string[];
picurl: string;
constructor(private db: AngularFireDatabase) {
this.picsUrl = [];
}
addSpot(spot: Spot){
this.spotsRef.push({
title: spot.title,
synopsis: spot.synopsis,
userId: spot.userId,
markerLatLng: spot.markerLatLng,
markerLatLngTwo: spot.markerLatLngTwo,
photo: spot.photo,
categories: spot.categories
});
}
}
my interface:
export interface Spot {
$key: string;
title: string;
synopsis: string;
userId: string;
markerLatLng: number[];
markerLatLngTwo: number[];
photo: string[];
categories: string[];
}
If someone can help me :) Thx a lot
Upvotes: 1
Views: 1635
Reputation: 978
Firebase's Firestore and Realtime Database don't allow customized keys in array fields. For that you need to create a sub-collection of images inside your document, where you can define a customized ID to each image.
Example:
galeries (collection)
|_gallery_1 (document with custom id)
-- title: Christmas (field)
-- date: 12/25/2019 (field)
-- photos: (collection)
|_photo_1 (document with custom id)
-- url: https://.../img.png (field)
|_photo_2...
There's a great tutorial for Firestore NoSQL Modelling on Youtube, I strongly recommend it: https://www.youtube.com/watch?v=jm66TSlVtcc
Upvotes: 0
Reputation: 598708
Since photo
is declared as a local array (photo: string[];
) in your JavaScript code, Firebase will write it as is to the database.
If you want to write the individual photos with push IDs, you'll have to write them separate from the other data, and call push()
for each of them:
let newRef = this.spotsRef.push({
title: spot.title,
synopsis: spot.synopsis,
userId: spot.userId,
markerLatLng: spot.markerLatLng,
markerLatLngTwo: spot.markerLatLngTwo,
categories: spot.categories
});
spot.photo.forEach((photo) => {
newRef.child("photo").push(photo);
})
The above is the simplest, but leads to multiple writer operations to the database. To get the same result in a single write operation, you can do something like:
let photos = {};
spot.photo.forEach((photo) => {
photos[this.spotsRef.push().key] = photo;
})
this.spotsRef.push({
title: spot.title,
synopsis: spot.synopsis,
userId: spot.userId,
markerLatLng: spot.markerLatLng,
markerLatLngTwo: spot.markerLatLngTwo,
photo: photos,
categories: spot.categories
});
Upvotes: 1