[英]How to add subcollection to a subcollection in firestore, react app
I create subcollection of budgets in collection of users like this:我在这样的用户集合中创建预算的子集合:
const addBudget = async (budget: Budget, userId: string) => {
await addDoc(collection(db, 'users', userId, 'budgets'), { name: budget.name, max: budget.max });
};
The id of the budget is auto generated, but then I want to add another subcollection in budgets:预算的 ID 是自动生成的,但我想在预算中添加另一个子集合:
const addExpense = async (expense: Expense, userId: string) => {
await addDoc(collection(db, 'users', userId, 'budgets', expense.budgetId /* auto generated id should be here here*/, 'expenses'), {
description: expense.description,
expenseValue: expense.expenseValue
});
};
This is my structure in firestore, but it doesnt work right now, it creates new budget id of 1 and then creates subcollection of expenses:这是我在 firestore 中的结构,但它现在不起作用,它创建新的预算 ID 1,然后创建费用的子集合:
How can I add this subcollection of expenses other way?我怎样才能以其他方式添加这个费用子集合?
The addDoc
function returns a DocumentReference
. addDoc
function返回一个DocumentReference
。 So if you capture that, you can read its id
and use that to create another subcollection under it.所以如果你捕获它,你可以读取它的id
并使用它在它下面创建另一个子集合。
const budgetRef = await addDoc(collection(db, 'users', userId, 'budgets'), { name: budget.name, max: budget.max });
const budgetId = budgetRef.id;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.