如何检查Firebase集合中是否已存在值?

时间:2019-03-09 19:28:42

标签: javascript firebase firebase-realtime-database

我有一个集合users/id/favorites,我想检查集合中是否已经存在一个值。当将数据推送到数据库时,firebase会自动生成密钥。我该怎么办?

enter image description here

这是我将数据推送到数据库的方式:

addToFavorites({ state }, payload) { 
firebase
    .database()
    .ref('users')
    .child(state.user.user.uid + '/favorites')
    .push(payload);
}

我想做类似的事情:

addToFavorites({ state }, payload) {
firebase
    .database()
    .ref('users/' + state.user.user.uid + '/favorites')
    .once('value', snapshot => {
        if (snapshot.magicFindKeyFunction(payload)) {
            firebase
                .database()
                .ref('users')
                .child(state.user.user.uid + '/favorites')
                .push(payload);
        }
    });
}

1 个答案:

答案 0 :(得分:0)

尝试以下操作:

exists()

<div class="row"> <div class="col-md-2"> <div class="form-group"> <label for="dataPrimayID">Date Primary</label> <input type="text" class="form-control datepickerDefault" id="dataPrimayID" name="dataPrimary" maxlength="250"> </div> </div> <div class="col-md-2"> <div class="form-group"> <label for="dataFinalID">Date Final</label> <input type="text" class="form-control datepickerDefault" id="dataFinalID" name="dataFinal" maxlength="250"> </div> </div> <div class="col-md-2"> <a id="btnSearch" class="btn btn-primary">Search</a> </div> </div> <div class="row"> <div class="table-responsive col-md-12"> <table id="dataTableHistoricoID" class="table table-striped" cellspacing="0" cellpadding="0"> <thead> <tr> <th>Name</th> <th>LastName</th> </tr> </thead> <tbody> <% if(data.length > 0){ %> <% for ( var i = 0 ; i < data.length ; i++){ %> <tr> <td> <%= data[i].name%> </td> <td> <%= data[i].lastname%> </td> </tr> <% } %> <% } %> </tbody> </table> </div> </div>

  

如果此DataSnapshot包含任何数据,则返回true。