首页 > 解决方案 > Firestore 文档查询

问题描述

所以我使用带有firebase firestore的Node JS,我想在一个包含文档的集合中创建一个查询,每个文档都有相同的布局,地图(随机ID)>地图(用户ID)> {name:“你好"},所以我想在整个集合中进行搜索,找到所有具有相同名称值的对象作为搜索文本,这里是数据库的图像,有什么方法可以复合这个查询?谢谢!!

数据库快照

标签: node.jsfirebasesearchgoogle-cloud-firestore

解决方案


您采用的方法的问题是第二个 randomId,随机性使得无法在单个查询中处理,因此我建议您为此目的更改该结构,如果您将结构更改为以下内容:

Desks Collection
    uid
    mapContent subCollection
        mapId
        userId
        color
        name

这基本上是同一件事,只是以子集合的方式组织,您可以使用以下代码查询它:

var arrayOfMaps = [];

var docRef = db.collection("Desks");

docRef.get().then(function(querySnapshot) {
    // In case you want to get only the mapContent document
    querySnapshot.forEach(function(doc) {
        arrayOfMaps.push(db.collection("Desks").doc(doc.id).collection("mapContent")
                           .where("name", "==", "Ikea").get());
    });
    // In case you want to get the whole desks document
    querySnapshot.forEach(function(doc) {
        var snapshot = db.collection("Desks").doc(doc.id).collection("mapContent")
                         .where("name", "==", "Ikea").get();
        if (!snapshot.empty){
            arrayOfMaps.push(doc);
        }
    });
})

推荐阅读