Firebase ServerValue.increment(1) doesnt work on cloud functions

Viewed 526

I'm trying to use the increment feature on the firebase admin sdk for node.js.
My function is deployed to cloud functions node version 10

here is the code

let admin = require('firebase-admin').initializeApp({
    databaseURL: "https://igibo-b0b27.firebaseio.com",
    projectId: "igibo-b0b27"
});

const igDatabase = admin.database();

exports.test = (req, res) => {

igDatabase.ref('test123').set(admin.database.ServerValue.increment(1));
res.status(200).send('ok');
};

here is the package.json

{
  "name": "authenticate",
  "version": "1.0.0",
   "dependencies": {
 
     "firebase-admin": "^9.1.1"
   }
}

but when i try to call the function i get TypeError: Cannot read property 'increment' of undefined

what am i doing wrong?

1 Answers

The way you're declaring admin isn't right for use with ServerValue. Use this instead:

let admin = require('firebase-admin')

admin.initializeApp({
    databaseURL: "https://igibo-b0b27.firebaseio.com",
    projectId: "igibo-b0b27"
});

const igDatabase = admin.database();

exports.test = (req, res) => {
    igDatabase.ref('test123').set(admin.database.ServerValue.increment(1))
    .then(() => { res.status(200).send('ok'); })
};

Also note that I added then to the call to set() because it's asynchronous and returns a promise. You need to use that promise to wait for the write to complete before sending the response.

Related