因此,我首先要说Google的Firebase文档太可怕了。当用户向电子商务网站上的购物车中添加商品时,我试图将子值附加到存储在Firestore db中的文档中的列表中。有史以来(或应该是)最简单的事情。所有文档都说使用.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 Realtime Database API的一部分,而不是Firestore API的一部分。虽然这两个数据库都是Firebase的一部分,但它们各自都有自己的API,并且不兼容。
要将文档添加到Firestore集合中,您可以执行以下操作:
var testRef = firebase.firestore().collection('Carts').doc(userUid);
testRef.set({
productName: productName,
productId: productId
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句