gpt4 book ai didi

javascript - 有什么方法可以自动增加 firebase 中的字段

转载 作者:行者123 更新时间:2023-12-01 01:21:24 25 4
gpt4 key购买 nike

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

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

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

最佳答案

您可以使用云函数轻松完成

// 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/

关于javascript - 有什么方法可以自动增加 firebase 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54200914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com