简体   繁体   中英

FieldValue.increment does not work but adds "operand"

I'm using a firebase database and a simple function with the new FieldValue.increment to increment a counter but that does not work but adds "operand" field without ever incrementing it.

My function is super simple:

exports.updateCounters = functions.https.onRequest((req, res) => {
  // grab the parameters.
  const username = req.query.username;

  var updateObject = { };
  updateObject[username] = admin.firestore.FieldValue.increment(1);
  admin.database().ref('counterstest').update(updateObject);
});

When I deploy and call this function I would expect to see

countertest: {
  myusername: 1
}

but I see

countertest: {
  myusername: {
    operand: 1
  }
}

instead and operand: 1 never increments even if I call my function multiple times.

Can somebody point out what error I'm making here?

Thank you!

FieldValue.increment() is a feature of Cloud Firestore, but you're apparently trying to apply it to Realtime Database. This is not going to work - they are different databases, and Realtime Database doesn't support atomic increments like this.

What you're actually doing here is writing the JSON representation of the returned FieldValue object to Realime Database. Apparently, internally, the FieldValue object has a property called "operand" which contains the value to increment by.

I know this post is a couple of years old, but database.ServerValue.increment works with the 11.X firebase-admin Realtime Database like so:

admin.database().ref('counterstest').update({ myusername: database.ServerValue.increment(1)  })

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