Ad

Parent Node Elimination Using Child Value

I am using firebase for my application and would like to be able to delete a parent node via its child value. I have already tried several solutions without achieving any results, this is my last attempt:

 exports.removePlayer = functions.https.onRequest(async (req, res) => {
   const idGiocatore = req.query.idGiocatore;
   const idStanza = req.query.idStanza;

   var ref = await admin.database().ref('/stanze/' + idStanza + "/giocatori");

   ref.orderByChild('id').equalTo(idGiocatore)
   .once('value').then(function (snapshot) {
    snapshot.forEach(function (childSnapshot) {
      //remove each child
      ref.child(childSnapshot.key).remove();
    });
   res.json({ success: "success" });
  });

However this code generates the following error:

40:3   error    Expected catch() or return                  promise/catch-or-return
41:25  warning  Unexpected function expression              prefer-arrow-callback
41:25  error    Each then() should return a value or throw  promise/always-return
42:24  warning  Unexpected function expression              prefer-arrow-callback
124:19  warning  Unexpected function expression              prefer-arrow-callback
125:22  warning  Unexpected function expression              prefer-arrow-callback
137:38  warning  Unexpected function expression              prefer-arrow-callback
139:22  warning  Unexpected function expression              prefer-arrow-callback

✖ 8 problems (2 errors, 6 warnings)
0 errors and 6 warnings potentially fixable with the `--fix` option.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\marco\AppData\Roaming\npm-cache\_logs\2020-06-07T09_10_36_095Z-debug.log

This is the structure of my realtime database:

enter image description here

In summary I would like to delete the "HOST" node via the child id: "host"

Using this code:

exports.removePlayer = functions.https.onRequest(async (req, res) => {
const idGiocatore = req.query.idGiocatore;
const idStanza = req.query.idStanza;

var ref = await admin.database().ref('/stanze/' + idStanza + "/giocatori");

ref.orderByChild('id').equalTo(idGiocatore).once('value')
  .then(snapshot => {

      const promises = [];
      snapshot.forEach(childSnapshot => {
          //remove each child
          promises.push(ref.child(childSnapshot.key).remove());
      });
      return Promise.all(promises);
   })
  .then(() => {
      res.status(200).json({ success: "success" });
   })
  .catch(error => {
      //See the doc
  });
});

It returns this error:

   50:13  error    Each then() should return a value or throw  
   promise/always-return
  133:19  warning  Unexpected function expression              prefer- 
  arrow-callback
  134:22  warning  Unexpected function expression              prefer- 
  arrow-callback
 146:38  warning  Unexpected function expression              prefer-arrow- 
 callback
 148:22  warning  Unexpected function expression              prefer-arrow- 
 callback

✖ 5 problems (1 error, 4 warnings)
0 errors and 4 warnings potentially fixable with the `--fix` option.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] lint script.
npm ERR! This is probably not a problem with npm. There is likely 
additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\marco\AppData\Roaming\npm-cache\_logs\2020-06- 
07T10_01_55_004Z-debug.log
events.js:288
  throw er; // Unhandled 'error' event
  ^

Error: spawn npm --prefix "%RESOURCE_DIR%" run lint ENOENT
at notFoundError 
  (C:\Users\marco\.cache\firebase\tools\lib\node_modules\cross- 
env\node_modules\cross-spawn\lib\enoent.js:6:26)
at verifyENOENT 
 (C:\Users\marco\.cache\firebase\tools\lib\node_modules\cross- 
env\node_modules\cross-spawn\lib\enoent.js:40:16)
at ChildProcess.cp.emit 
 (C:\Users\marco\.cache\firebase\tools\lib\node_modules\cross- 
env\node_modules\cross-spawn\lib\enoent.js:27:25)
at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
Emitted 'error' event on ChildProcess instance at:
at ChildProcess.cp.emit 
(C:\Users\marco\.cache\firebase\tools\lib\node_modules\cross- 
env\node_modules\cross-spawn\lib\enoent.js:30:37)
at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12) {
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn npm --prefix "%RESOURCE_DIR%" run lint',
path: 'npm --prefix "%RESOURCE_DIR%" run lint',
spawnargs: []
}

Error: functions predeploy error: Command terminated with non-zero exit 
code1
Ad

Answer

The remove() method is asynchronous and returns a Promise.

In addition, you want to execute, in parallel, several calls to this method: you therefore need to use Promise.all(), in order to wait for all the Promises to resolve before sending back the response.

The following modifications should do the trick:

exports.removePlayer = functions.https.onRequest(async (req, res) => {

    try {
        const idGiocatore = req.query.idGiocatore;
        const idStanza = req.query.idStanza;

        const ref = admin.database().ref('/stanze/' + idStanza + "/giocatori");   
        //Note that, in the above line, there is no need for await, ref() is not asynchronous

        const snapshot = await ref.orderByChild('id').equalTo(idGiocatore).once('value');
        // Note that you need await in the above line!

        const promises = [];
        snapshot.forEach(childSnapshot => {
            promises.push(ref.child(childSnapshot.key).remove());
        });

        await Promise.all(promises);

        res.status(200).json({ success: "success" });
    } catch (error) {
        //See the first video of the series mentioned below
    }

});

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

Ad
source: stackoverflow.com
Ad