gpt4 book ai didi

javascript - 如何在 Javascript 前端使用 Firebase Firestore .push() 方法

转载 作者:行者123 更新时间:2023-11-28 03:11:37 24 4
gpt4 key购买 nike

首先我要说的是,Google 的 Firebase 文档非常糟糕。当用户将商品添加到电子商务网站上的购物车时,我尝试将子值附加到存储在 Firestore 数据库中的文档中的列表中。有史以来最简单的事情(或应该是)..所有文档都说使用 .push() ,但没有一个可操作的示例来说明如何实现它。这还不足以让我理解如何使用它:

// Create a new post reference with an auto-generated id
var newPostRef = postListRef.push();
newPostRef.set({
// ...
});

postListRef 从哪里来以及如何实例化与 .push() 一起使用的引用?在过去的三天里,我一直在断断续续地猜测如何使用该函数,从获取数据库引用到添加值。以下是我尝试使用它的两种方法。这是一个非常简单的问题,它让我发疯,经过几个小时的谷歌搜索后,我在任何地方都找不到一个完整的例子。请用示例代码提供完整的解释,其中的细节对您来说似乎是不必要的,关于如何在普通的 javascript 前端脚本中使用 firestore 实现 .push() !如果您能解释如何从列表中删除单个项目,则可获得奖励分。

文档链接: https://firebase.google.com/docs/database/web/lists-of-data , https://firebase.google.com/docs/database/admin/save-data

const db = firebase.firestore();
//set with a function that checks to see if user is logged in
var userUid;
//set if the user is not signed in to persist the cart
var guestUid;

function addItemToCart() {
console.log("Add item to cart triggered..");
const productName = "Assorted Oranges";
const productId = "123";

if (userUid != null) {
var testRef = firebase.firestore().collection('Carts').doc(userUid).push();
testRef.set({
productName: productName,
productId: productId });
} else {
guestUid = getUUID();
var testRef = db.push({
productName: productName,
productId: productId
});
}
}

无论我如何尝试使用它,我都会不断收到错误的变体:.push() 不是这样的函数:

product-single:126 Uncaught TypeError: firebase.firestore(...).collection(...).doc(...).push is not a function
at addItemToCart (product-single:126)

最佳答案

push() 方法是 Firebase 实时数据库 API 的一部分,而不是 Firestore API 的一部分。虽然这两个数据库都是 Firebase 的一部分,但它们都有自己的 API 并且不兼容。

add a document to a Firestore collection ,你会这样做:

var testRef = firebase.firestore().collection('Carts').doc(userUid);
testRef.set({
productName: productName,
productId: productId
});

关于javascript - 如何在 Javascript 前端使用 Firebase Firestore .push() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60049081/

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