有什么办法可以自动增加Firebase中的字段

时间:2019-01-15 14:30:34

标签: javascript firebase google-cloud-firestore

我想为每个添加到Firestore数据库的新商品自动增加库存编号。 (不使用push()方法)

库存编号是受控编号,每次添加一个新字段时,必须唯一并将其递增1,而无需我手动指定库存编号。

请记住-是初学者,并且不具备Firebase的深入知识。

1 个答案:

答案 0 :(得分:1)

您可以使用Cloud Functions轻松完成

// Change '/COLLECTION/{DOC}' to which document do you want to increment the counter when it's created
exports.counter = functions.firestore.document('/COLLECTION/{DOC}').onCreate((snap, context) => {
  const db = admin.firestore();

  // Change 'counter/ref' to where do you want to increment
  const countRef = db.doc('counter/ref');
  return db.runTransaction(t => {
    return t.get(countRef).then(doc => {
      const counter = (doc.data().counter || 0) + 1;
      t.update(countRef, {counter: counter});
    });
  });
});

您可以在https://firebase.google.com/docs/functions/

上了解有关云功能的更多信息
相关问题