Firebase orderByChild忽略

时间:2017-01-15 23:23:25

标签: javascript firebase firebase-realtime-database

如何通过sortOrder对Firebase中的以下结构进行排序?

categories {
    {
        "b": {
            "name": "Banana",
            "sortOrder": 2
        },
        "a": {
            "name": "Apple",
            "sortOrder": 1
        }
    }
}

从文档中看起来很简单:

ref('categories').orderByChild('sortOrder').once('value') ...

但是,返回的第一个节点是banana。使用什么字符串值并不重要。例如,以下内容返回相同的结果:

ref('categories').orderByChild('xxx').once('value') ...

全功能:

public list(): Observable<Category[]> {

    let ref = firebase.database().ref('categories').orderByChild('sortOrder');

    return Observable.fromPromise(<Promise<any>>ref.once('value'))
        .flatMap(snapshot => {
            let objects = snapshot.val();
            let categories: Array<Category> = new Array();

            for (let key in objects) {
                let category: Category = objects[key];
                category.code = key;
                categories.push(category);
            }

            return Observable.of(categories);
        }
    );
}

1 个答案:

答案 0 :(得分:0)

问题在于,当您通过快照的值键访问子项时,顺序是不确定的。

您需要使用快照的forEach方法:

return Observable.fromPromise(<Promise<any>>ref.once('value'))
    .flatMap(snapshot => {
        let categories: Array<Category> = new Array();
        snapshot.forEach(childSnapshot => {
            let category: Category = childSnapshot.val();
            category.code = childSnapshot.key;
            categories.push(category);
        });
        return Observable.of(categories);
    }
);

此外,您可以使用map并返回categories