gpt4 book ai didi

javascript - 需要使用 val() 将对象插入 firebase 数组

转载 作者:行者123 更新时间:2023-11-30 20:38:47 25 4
gpt4 key购买 nike

我最近开始使用 React.js 进行 Firebase 开发 -

目前,我正在尝试从数据库中提取数据并使用数据创建一个新对象。

这是代码:

var arr = firebase.database().ref("news");//this is the ref.

arr.once('value', function (snapshot) {//will return the array value
model = {//this is the model i want to .push()
title: title,
content: content,
img: img,
category: category,
likes: likes,
id: snapshot.val().length//This is where I want to add the arr.length
};

var promise = arr.push(model);

promise.then(function(){
...
})
})

问题是 arr.push(model) 在加载 model.id 变量之前运行。

最佳答案

这里发生的是 snapshot.val() 返回一个对象而不是数组。因此,如果您尝试访问 snapshot.val().length,它将返回 undefined。

现在的解决方案是将对象转换为数组以获取计数。

id: Object.keys(snapshot.val()).length

这可能会解决您的问题。

抱歉,如果这不是您要找的。

关于javascript - 需要使用 val() 将对象插入 firebase 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49514045/

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