So I'm having a problem that I can't think else how can I add another collection in the parent/first collection let say the diagram should something look like this
owner-item:
group-item: [],
single-item: []
Let say in firebase-collection.js
it look something like this
import { collection } from 'firebase/firestore'
import { db } from './firebase'
export const owneritemsRef = collection(db,'owner-items')
And then now I'm exporting now the collection by something like this
let uploadUserStorageTask = uploadBytesResumable(list[i],pictures[j].data)
....
},(err) => {
console.log(err)
},() => {
getDownloadURL(uploadUserStorageTask.snapshot.ref)
.then(async (downloadURL) => {
await setDoc(doc(db,`owner-items`,`${currentUser?.email}-${uid}`),{
creator:username,name:name,img:downloadURL,email:currentUser?.email
})
.then( res => {})
.catch(err => {})
})
})
but because I have group-images I want them to set in a group-item collection but I was thinknig await setDoc
or something else I should added to make it like a group-item collection in the owner-item
parent collection but how can I do it?
I search something related to it and it something like this maybe? LINK...but I want setDoc
because I can change my document_id
UPDATE It is something like this.... LINK
import { doc } from "firebase/firestore";
const messageRef = doc(db, "rooms", "roomA", "messages", "message1");
I'm sorry its about document inside of collection...let say
await setDoc(..., {
group_item: {},
single_item: {},
}
based on my old snippet just add this new thing... Is this the righht way to do it? or something like subcollection you know what I mean.
UPDATE 2
let say I have owner-items
await setDoc(doc(db,`owner-items`,`${currentUser?.email}-${uid}`),{
group_items:[{
id:1,
img:file-image
}],
single_item:[{
id:1,
img:file-image
}]
})
CodePudding user response:
If I understand correctly your answer and comments, the following, using a batched write, should do the trick.
import { writeBatch, doc } from "firebase/firestore";
const batch = writeBatch(db);
const parentDocRef = doc(db, `owner-items`, `${currentUser?.email}-${uid}`);
batch.set(parentDocRef, {
single_item: [{
id: 1,
img: file - image
}]
});
const group_items = [
{
id: 1,
img: file - image
},
{...}
];
group_items.forEach(elem => {
const groupItemDocRef = doc(db, `owner-items`, `${currentUser?.email}-${uid}`, 'group-items');
batch.set(groupItemDocRef, {
item: elem
});
});
await batch.commit();
Note that a batched write can contain up to 500 operations, so your group_items
array shall have maximum 499 elements.