将 2 个文档添加到 firestore 一个是使用另一个的引用?
adding 2 documents to firestore one is using a reference from the other?
我正在尝试创建 2 个文档,其中第一个文档 ID 在第二个文档中使用。一个问题是我的代码看起来有线,尤其是链接。恐怕即使有效也可能是错误的。
有没有更清晰的重构想法?流程如下:
- 注册一个用户
- 获取他创建的id创建了一个新的collection
- 然后获取新的 collection ID
- 使用用户 ID 创建最终文档,并将之前创建的 collection 的 ID 作为最后一个文档的参考。
const Signup = async (email: string, password: string) => {
await createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
const colRef = collection(db, 'Shared');
addDoc(colRef, {
sharedValue: '',
}).then((res) =>
setDoc(doc(db, 'Data', user.uid), {
sharedId: res.id,
})
);
})
.catch((error) => {
console.log(error)
});
};
如 adding a document 上的文档所示:
In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc()
.
import { collection, doc, setDoc } from "firebase/firestore";
// Add a new document with a generated id
const newCityRef = doc(collection(db, "cities"));
// later...
await setDoc(newCityRef, data);
所以:
await createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
const colRef = collection(db, 'Shared');
const docRef = doc(db, 'Shared');
setDoc(docRef, {
sharedValue: '',
}).then((res) =>
setDoc(doc(db, 'Data', user.uid), {
sharedId: docRef.id,
})
);
})
.catch((error) => {
console.log(error)
});
};
我正在尝试创建 2 个文档,其中第一个文档 ID 在第二个文档中使用。一个问题是我的代码看起来有线,尤其是链接。恐怕即使有效也可能是错误的。
有没有更清晰的重构想法?流程如下:
- 注册一个用户
- 获取他创建的id创建了一个新的collection
- 然后获取新的 collection ID
- 使用用户 ID 创建最终文档,并将之前创建的 collection 的 ID 作为最后一个文档的参考。
const Signup = async (email: string, password: string) => {
await createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
const colRef = collection(db, 'Shared');
addDoc(colRef, {
sharedValue: '',
}).then((res) =>
setDoc(doc(db, 'Data', user.uid), {
sharedId: res.id,
})
);
})
.catch((error) => {
console.log(error)
});
};
如 adding a document 上的文档所示:
In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call
doc()
.import { collection, doc, setDoc } from "firebase/firestore"; // Add a new document with a generated id const newCityRef = doc(collection(db, "cities")); // later... await setDoc(newCityRef, data);
所以:
await createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
const colRef = collection(db, 'Shared');
const docRef = doc(db, 'Shared');
setDoc(docRef, {
sharedValue: '',
}).then((res) =>
setDoc(doc(db, 'Data', user.uid), {
sharedId: docRef.id,
})
);
})
.catch((error) => {
console.log(error)
});
};