简体   繁体   中英

How to get a child key name randomly from the Firebase Realtime database with a Javascript cloud function

I want to randomly get a child key from the pickers section and then add data to it from another node. I want to do all of this with a JavaScript Cloud Function. Here is my code.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.onDataAdded = functions.database.ref('/Pickup-Requests/{uid}').onCreate((snapshot, context) => {

    const getRandomPickerid =    
        database.ref('/Pickers').once('value').then(event => {
        const pickerUid =  Object.keys()[random];
        return pickerUid;
    })
    .catch(error => {
        console.error("Error", error);

    });

    const pickerUid = getRandomPickerid;

    const data = snapshot.val();
    const newData = data;
    return snapshot.ref.parent.child(pickerUid).set(newData);

});

图片

How can I do this?

The following should do the trick:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

function randomKey(obj) {
    var keys = Object.keys(obj);
    return keys[(keys.length * Math.random()) << 0];
}

exports.onDataAdded = functions.database.ref('/Pickup-Requests/{uid}').onCreate((snapshot, context) => {

    const db = admin.database();
    const data = snapshot.val();

    return db.ref('/Pickers').once('value')
    .then(snapshot => {
        const pickerUid = randomKey(snapshot.val()); 
        return snapshot.ref.parent.child(pickerUid).set(data);
    })

});

I would suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/

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