简体   繁体   中英

How to check if a value already exists in a Firebase Collection?

I have a collection users/id/favorites and i want to check if a value already exists in the collection. Keys are auto generated by firebase when data is pushed to the database. How can I do that?

在此输入图像描述

This is how i push data to the db:

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

I would like to do something like:

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);
        }
    });
}

Try the following:

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

exists() :

Returns true if this DataSnapshot contains any data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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