通过ID获取子集合中的单个文档

huangapple go评论79阅读模式
英文:

Get a single doc inside subcollection by Id

问题

以下是您要翻译的代码部分:

[![enter image description here][1]][1]

How can i get a single document data inside a subcollection by his id so i can show just a single workout info inside a component?

export default function WorkoutInfo(props){
const [workout,setWorkout]=useState({});
const [workoutName,setWorkoutName] = useState("");
const workoutsCollectionRef = collection(db,"users",props.userId,"workouts");

useEffect(()=>{
    const queryWorkouts = query(workoutsCollectionRef)
    const unsuscribe= onSnapshot(queryWorkouts,(snapshot)=>{
        let workout={};
        snapshot.forEach((doc)=>{
            if(doc.id==props.workotId)
                workout=({...doc.data(),id:doc.id});
        })
        setWorkout(workout);
    })

    return () => unsuscribe();
},[])}

在此提供了代码的中文翻译。

英文:

通过ID获取子集合中的单个文档

How can i get a single document data inside a subcollection by his id so i can show just a single workout info inside a component?

export default function WorkoutInfo(props){
const [workout,setWorkout]=useState({});
const [workoutName,setWorkoutName] = useState("");
const workoutsCollectionRef = collection(db,"users",props.userId,"workouts");

useEffect(()=>{
    const queryWorkouts = query(workoutsCollectionRef)
    const unsuscribe= onSnapshot(queryWorkouts,(snapshot)=>{
        let workout={};
        snapshot.forEach((doc)=>{
            if(doc.id==props.workotId)
                workout=({...doc.data(),id:doc.id});
        })
        setWorkout(workout);
    })

    return () => unsuscribe();
},[])}

What's wrong with this code?

答案1

得分: 0

如果props.workotId是您想要加载的训练文档的文档ID,您可以使用以下方式进行监听:

useEffect(() => {
    const documentRef = doc(workoutsCollectionRef, props.workotId);
    const unsubcribe = onSnapshot(documentRef, (doc) => {
        setWorkout({...doc.data(), id: doc.id});
    })

    return () => unsubcribe();
}, [])
英文:

If props.workotId [sic] is the the document ID of the workout document you want to load, you can listen to it with:

useEffect(()=>{
    const documentRef = doc(workoutsCollectionRef, props.workotId);
    const unsubcribe= onSnapshot(documentRef,(doc)=>{
        setWorkout({...doc.data(),id:doc.id});
    })

    return () => unsubcribe();
},[])}

huangapple
  • 本文由 发表于 2023年7月18日 05:22:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定