【问题标题】:Is there any way to auto increment a field in firebase有什么方法可以自动增加firebase中的字段
【发布时间】:2019-01-15 14:30:33
【问题描述】:

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

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

请记住 - 我是初学者,对 firebase 没有深入的了解。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案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/了解更多关于 Cloud Functions 的信息

    【讨论】:

      猜你喜欢
      • 2012-09-12
      • 2015-02-21
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      相关资源
      最近更新 更多