nodejs firebase error RangeError: Maximum call stack size exceeded failure

noam aghai picture noam aghai · Jan 26, 2017 · Viewed 7.5k times · Source

I have an error from the firebase :

FIREBASE WARNING: Exception was thrown by user callback. RangeError: Maximum call stack size exceeded

I didn't find my mistake.

I'm very lost in here, please help.

My code looks like this:

app.post('/updateCoords', (req, res)=>{
    var usrID = req.body.id;
    var usrCoords = {
        lat: req.body.lat,
        long: req.body.long
    }
    console.log('userID : '+usrID+' lat : '+usrCoords.lat+' long : '+usrCoords.long);
    var ref = database.ref('users');
    try{
        ref.orderByChild('username').equalTo(usrID).on("value", (snapshot)=> {
            if(!snapshot.val()){
                // Error
                return res.json({msg: 'username is not in D.B', success: false});
            }
            // Success
            admin.database().ref('users/' + usrID + '/currentLocation').update({
                lat: usrCoords.lat,
                long: usrCoords.long
            });
            return res.json({msg: 'user coords changed', success: true});
        });
    }catch(ex){
        console.log('ex /updateCoords = '+ex);
    }
});

Answer

Frank van Puffelen picture Frank van Puffelen · Jan 26, 2017

You're updating the same node that you're reading. This causes the on("value" callback to be triggered again. Which in turn then writes a new value, which trigger the callback again. And that continues until the runtime runs out of call stack space.

The simplest solution is to use once() instead of on():

   var ref = database.ref('users');
    try{
        ref.orderByChild('username').equalTo(usrID).once("value", (snapshot)=> {
            if(!snapshot.val()){
                checker = true;
            }

            if(snapshot.val()){
                admin.database().ref('users/' + usrID + '/currentLocation').update({
                    lat: usrCoords.lat,
                    long: usrCoords.long
                });
                return res.json({msg: 'user coords changed', success: true});
            //  checker = false;
            }


            // res.json({msg: 'username is not in D.B', success: false});

        });
    }catch(ex){
         console.log('ex /updateCoords = '+ex);
    }