使用Firebase Javascript API按值查找元素

使用Firebase Javascript API按值查找元素,javascript,html,firebase,Javascript,Html,Firebase,这是我为表格添加新颜色的代码,它工作正常,Firebase仪表板显示每种颜色都添加了一个新id到颜色表格: // example pushColor('yellow') { function pushColor(colorName) { var colorsRef = fireBaseRef.child("colors"); colorsRef.push(colorName, function(error) { if (error) {

这是我为表格添加新颜色的代码,它工作正常,Firebase仪表板显示每种颜色都添加了一个新id到颜色表格:

// example pushColor('yellow') {
function pushColor(colorName) {

    var colorsRef = fireBaseRef.child("colors");
    colorsRef.push(colorName, function(error) {
        if (error) {
            alert("Color could not be saved." + error);
        }
    });
}
但是,在添加新颜色之前,我希望确保表中不存在我要添加的颜色。以下是我迄今为止的尝试:

function colorExists(colorName) {
    var colorsRef = fireBaseRef.child("colors");

    colorsRef.once('value', function(snapshot) {
        exists = (snapshot.val() !== null);
        if (exists) {
            alert(colorName + ' exists!');
        } else {
            alert(venueName + ' does not exist!');
        }
    });
}
问题是,当我提交表单时,会出现以下行为: 第一次检查颜色“黑色”(空表):

我加黑色作为一种颜色

第二次检查颜色“黑色”:

…到目前为止,一切都很好。但如果我提交颜色“紫色”(不在数据库中),我会得到:

插入第一种颜色后搜索的任何内容都返回“存在!”


我猜我不理解colorExists()方法的工作方式,有没有人能给我指出修复此函数的正确方向,使其满足我的需要,或者帮助我找到相关文档,以通过其值之一查找实体?

发布此消息后,我发现了它。。。我需要将colorExists方法更新为以下内容(代码可能需要一些清理,但我希望每个人都能看到我所做的更改):

"black does not exist!"
"black exists!"
"purple exists!"
function colorExists(colorName) {
    var colorsRef = fireBaseRef.child("colors");

    colorsRef.once('value', function(snapshot) {
        if (snapshot !== null) {

           snapshot.forEach(function(snapshot) {

                // if the value matches the name we specified
                if (snapshot.val() === colorName) {

                    exists = true;
                    return;
                }
            });

            if (exists) {
                alert(venueName + ' exists!');
            } else {
                alert(venueName + ' does not exist!');
            }
        });
}