如何获取where子句firestore的文档引用



如何获得对where子句结果的引用?我的数据库结构如下:

- Restaurants
- Restaurant 1
- Ratings (sub collection)
- Statistics

所以我有一个餐厅集合,每个医生都是特定的餐厅。在每个文档中,都有一个子集合,叫做ratings。我正试图获得一份关于1号餐厅的文档参考,这样我就可以添加一些一般统计数据,还可以获得一个子集合的参考,这样我们就可以添加一个评级。我目前一直在获取餐厅1的引用,因为我使用了where子句,该子句不返回引用。

var restaurantRef = firestore.collection("restaurants").where("name", "==", "Neubig Hall")
function addFeedback(data) {
return firestore.runTransaction((transaction) => {
var feedbackRef = restaurantRef.get().then(snapshot => {snapshot.forEach(doc => doc.ref.collection("feedback"))});

它说restaurantRef不是一个文件参考。我正在React Native应用程序中使用此功能。

从API文档中可以看到,其中((返回一个Query对象。它不是DocumentReference。

即使您认为查询只返回一个文档,您仍然需要编写代码来处理它可能在QuerySnapshot对象中返回零个或多个文档的事实。我建议查看有关查询的文档以查看示例。

还要注意,不能在事务中使用Query对象。事务需要DocumentReference,但这里没有。

如果你确实想执行查询并处理它返回的文档,它会更像这样:

const restaurantQuery = firestore.collection("restaurants").where("name", "==", "Neubig Hall")
restaurantQuery.get().then(querySnapshot => {
if (!querySnapshot.empty) {
const snapshot = querySnapshot.docs[0]  // use only the first document, but there could be more
const documentRef = snapshot.ref  // now you have a DocumentReference
//  ... use your DocumentReference ...
}
else {
// decide what you want to do if the query returns no documents.
}
})

您的代码中有一个拼写错误:您在restaurant末尾用e调用restauranteRef.get(),而您的查询被声明为restaurantRef,而没有e

你应该做:

function addFeedback(data) {
return firestore.runTransaction((transaction) => {
var feedbackRef = restaurantRef.get()then(...)   // <- without e
// ...
}

最新更新