gpt4 book ai didi

javascript - Firebase 函数 - 计算子项并更新条目

转载 作者:行者123 更新时间:2023-11-30 14:31:10 26 4
gpt4 key购买 nike

一直在尝试用Firebase Functions写一个简单的方法,但是对JS不熟。

下面是我的实时数据库的结构

-spots

---is_hidden: false

---likes

------like_id_1: true

---dislikes

------dislike_id_1: true

我正在尝试编写一个执行以下操作的简单方法:每当将一个条目添加到不喜欢时,计算喜欢和不喜欢的次数。

If the number of dislikes is larger than the number of ( likes + 5 ), change the value of is_hidden to true

这是我解决问题的尝试

exports.checkHiddenStatus = functions.database.ref('/spots/{spotid}').onWrite(
(change, context) => {
const collectionRef = change.after.ref;
const isHiddenRef = collectionRef.child('is_hidden');
const likesRef = collectionRef.child('likes');
const dislikesRef = collectionRef.child('dislikes');


if(isHiddenRef.before.val()) return;

let likeCount = likesRef.numChildren();
let dislikeCount = dislikesRef.numChildren();

let isHidden = false;

if( dislikeCount >= (likeCount + 5))
isHidden = true;

if(!isHidden) return;

// Return the promise from countRef.transaction() so our function
// waits for this async event to complete before it exits.
return isHiddenRef.transaction((current) => {
return isHidden;
}).then(() => {
return console.log('Counter updated.');
});
});

可悲的是,因为我没有使用 JS 的经验,所以我一直被我不理解的错误消息所困扰。最近的存在

TypeError: Cannot read property 'val' of undefined at exports.checkHiddenStatus.functions.database.ref.onWrite (/user_code/index.js:28:28)

有人可以帮我写这个函数吗?谢谢!

最佳答案

看起来您正在尝试处理数据库 Reference像 Change 对象一样的对象。更改具有 beforeafter 属性,但引用没有。

如果你有一个数据库引用对象,并且你想要数据库在那个位置的值,你需要用它的once()来查询它。方法。

阅读更多关于 reading 的信息和 writing使用 Admin SDK 的数据。

关于javascript - Firebase 函数 - 计算子项并更新条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51142656/

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