Tjb*_*187 2 javascript firebase vue.js google-cloud-firestore
我正在使用vue.js和firebase构建一个基本的CRUD应用程序。我正在尝试建立收藏夹功能,并遇到了存储数据的持久性问题。
当使用单击添加到收藏夹按钮时,我正在尝试将文档ID添加到“用户个人资料”文档中的数组。这是代码:
export function addNewUserAction (type, key, userID){
console.log(userID);
console.log(key);
firebase.firestore().collection('userActions').add({
type: type,
listing: key,
user: userID,
time: Date.now()
})
if(type === 'favorite'){
var sendfav = db.collection('userProfiles').doc(userID).update({
favs: firebase.firestore.FieldValue.arrayUnion(key)
});
}else if(type === 'xout'){
var sendxout = db.collection('userProfiles').doc(userID).update({
xouts: firebase.firestore.FieldValue.arrayUnion(key)
});
}else{
console.error(type + " is not a user action");
}
}
Run Code Online (Sandbox Code Playgroud)
我在控制台中收到以下错误:
Uncaught TypeError: Cannot read property 'arrayUnion' of undefined
at addNewUserAction
Run Code Online (Sandbox Code Playgroud)
我已经导入了Firebase和db ref,并通过每个引用运行了一个假的.set(),以确认它们指向的位置正确。我已经在'userProfile'文档中创建了数组。
Firebase安装是最新的,就像上周一样,因此我应该在构建中具有该功能。
似乎arrayUnion不能正常工作。有任何想法吗?其他的Firestore函数正在运行,因此我不确定。我会很无聊吗?谢谢
我遇到过同样的问题...
这行不通
import { fireStore } from '../../firebase';
....
fireStore.collection("users").doc(props.uid).update({
points: fireStore.FieldValue.arrayUnion({value: pointObj.value, reason: pointObj.reason})
});
Run Code Online (Sandbox Code Playgroud)
我更改了导入并使用了 Firebase Docs 中的确切代码。
这工作正常。
import * as firebase from 'firebase';
....
fireStore.collection("users").doc(props.uid).update({
points: firebase.firestore.FieldValue.arrayUnion({value: pointObj.value, reason: pointObj.reason})
});
Run Code Online (Sandbox Code Playgroud)
希望有帮助。
如果您使用的是Admin SDK
我正在尝试一些类似的随机错误。原来是因为我使用的是Firebase admin sdk,与Web SDK文档相比,它需要稍作更改。如果您使用的是Firebase管理员,请更换
firebase.firestore.FieldValue.arrayUnion(...
与
admin.firestore.FieldValue.arrayUnion(...
只是想更新这个。我可以通过以下方式导入 firebase 来实现此功能:
`import firebase from "firebase/firebase";`
Run Code Online (Sandbox Code Playgroud)
我认为我之前的问题有几个问题,第一个主要是没有正确的版本。我最近刚刚更新到 5.8.4,这完全破坏了我的应用程序。我尝试了上述作为可能的解决方案,它让我的应用程序再次运行。这促使我尝试使用 arrayUnion 并成功了。希望这对某人有帮助。感谢大家的帮助。
2019 年 10 月 11 日更新 所以我想对此添加另一个更新,以防新接触 firebase 的人像我一样追赶他们的尾巴。
因此,我上面包含的解决方案有效,因为它使用整个 firebase SDK 包(“firebase/firebase”),这很好,但是您将导入整个 firebase 包,这并不理想。您不断地在控制台中看到一条警告,表明您正在使用开发 SDK
如果您尝试优化您的应用程序并且仅导入所需的 firebase 包(即身份验证、数据库等),则需要从“firebase/app”导入 firebase 应用程序对象,然后导入所需的包。关键是按照 firebase 文档的要求导入为对象:
import * as firebase from 'firebase/app';
Import 'firebase/auth'
如果您使用:
import firebase from 'firebase/app'这是行不通的。
希望对某人有帮助。我知道这是很奇怪的事情,但它在我的学习曲线上困扰了我一段时间。