简体   繁体   English

Angular Firestore使用查询获取单个文档

[英]Angular Firestore Get Single Document With Query

I'm using Google Firestore. 我正在使用Google Firestore。 There is a collection called Universities, where each document represents a university. 有一个名为Universities的集合,每个文档代表一所大学。

How do I find a university by its name and update its view_count by +1? 如何按名称查找大学并将其view_count更新为+1?

[Collection: Universities]:
  [Document: 0JsaLtcfdDaEtHLMlMrh]:{
                      name: The University of Sydney,
                      view_count: 1
            };
   [Document: K2z7DMhKreyDniGUpo2t]:{
                      name: University of New South Wales,
                      view_count: 2
            }

You can do something like this: 你可以这样做:

db.collection("Universities").where("name", "==", "The University of Sydney")
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            //console.log(doc.id, " => ", doc.data());
            var docData = doc.data();
            var updatedCount = docData.view_count + 1;
            var universityRef = db.collection('Universities').doc(doc.id);
            var setWithMerge = universityRef.set({
                                    view_count: updatedCount
                                }, { merge: true });

        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

So, here what you can do is first query in collection using where to get all docs with specific name, then inside querySnapshot you'll get one doc object & then you can create reference of that document & update (overwrite) its view_count property value using set method with merge: true to keep other property values as it's. 所以,这里你可以做的是首先在集合中查询使用where获取具有特定名称的所有文档,然后在querySnapshot你将获得一个doc对象然后你可以创建该文档的引用并更新(覆盖)其view_count属性值使用带有merge: true set方法merge: true来保持其他属性值。

Follow offcial docs: Add data , Get data 关注官方文档: 添加数据获取数据

Note: This's generic web JS solution. 注意:这是一般的Web JS解决方案。 You can use same logic & write typescript code in angular app 您可以在角度应用程序中使用相同的逻辑和编写打字稿代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM