在具有多个文档的集合中查询文档ID

时间:2020-09-24 02:31:30

标签: reactjs firebase google-cloud-firestore

我有一个名为artworks的集合,其中包含两个文档:

kvAKyzz8duHJefihekpr

artist: "Pablo Picasso"
status: true

pCETdBNd0B6nm60BD15b

artist: "Franz Klein"
status: true

问题 如何从集合中获取文档ID(例如kvAKyzz8duHJefihekpr),然后将其作为道具传递?

const [artworks, setArtworks] = useState([]);
  
  useEffect(() => {
    db.collection("artworks").onSnapshot((snapshot) =>
      setArtworks(snapshot.docs.map((doc) => doc.data()))
    );
  }, []);

  return (
    <div className="review__board">
      
      <div>
        {artworks.map((artwork) => (
          <ReviewCard
            artist={artwork.artist}
           // pass in id as a prop??? id={artwork.id}
          />
        ))}
      </div>
    </div>

换句话说,如何查询集合中的文档ID,然后将其用作道具?

这是我收藏的形状:

enter image description here

1 个答案:

答案 0 :(得分:1)

一种方法是:

db.collection("artworks").onSnapshot((snapshot) =>
  setArtworks(snapshot.docs.map(doc => ({...doc.data(), id: doc.id})))
);

我喜欢使用Object.defineProperty将id附加到数据。这样,当写回Firestore时,数据库中将没有id字段(除非您打算使用它)。

const fromFirestore = (doc) => {
  const data = doc.data();
  Object.defineProperty(data, 'id', {value: doc.id})
  return data;
}

db.collection("artworks").onSnapshot((snapshot) =>
  setArtworks(snapshot.docs.map(fromFirestore))
);