首页 > 解决方案 > 用 Firestore 中的字段填充数组?

问题描述

所以我想用来自firestore的数据填充一个数组,我只是不确定如何做到这一点。

我有这个访问项目的用户信息和数据快照:

auth.onAuthStateChanged(user => {

  if (user) {
    db.collection('items').onSnapshot(snapshot => {
      setupItems(snapshot.docs);
      setupUI(user); 
      userDetails(user);
     }, err =>{
      console.log(err.message);
     })
  } else {
    setupUI();
    setupItems([]);
    userDetails();
  }
}); 

这适用于我项目的另一部分,用我的“项目”集合中的详细信息填充模板文字,还允许我访问用户集合中的当前用户 UID 及其特定文档。

我目前有这个硬编码:

const products = [
  {
    id: 1,
    img: './cod.jpeg',
    name: 'Call of Duty',
    price: 3,
    cart: false,
    quantity: 1,
    total: 0

  },
  {
    id: 2,
    img: './fonv.jpeg',
    name: 'Fallout:New Vegas',
    price: 4,
    cart: false,
    quantity: 1,
    total: 0
  },
  {
    id: 3,
    img: './ror2.jpeg',
    name: 'Risk of Rain 2',
    price: 5,
    cart: false,
    quantity: 1,
    total: 0

  }
];

我在firestore中的项目集合中也有完全相同的字段,即文档A有一个带有apple的字符串字段名称,带有url的字符串字段img,带有数字的整数字段price等。

有没有办法做到这一点,例如:

const products = [
{ 

id: filled by firebase,
img: filled by firebase,
name: filled by firebase,
price: filled by firebase,
cart: false,
quantity: 1,
total: 0
}

我知道我会添加一个 foreach 循环而不是对每个项目进行编码,但我不确定如何分配字段与硬编码。

编辑

添加后:

const itemsx = (data) => {
  if (data.length) {

    data.forEach(doc => {
    const item = doc.data();


products = [
  {
    id: item.uid,
    img: item.artwork,
    name: item.gamename,
    price: item.price,
    cart: false,
    quantity: 1,
    total: 0

  }

];
console.log(products)
});
} else {
console.log('If you see this, preschoolers are more competent than you at this point.');
}
}

我在控制台中得到了正确的输出,但是 products[] 被困在 itemsx 中并且不再全局可访问。(我将 itemsx(snapshot.docs) 添加到 onAuthStateChange 方法中)

我做错了什么,我知道我做错了什么,我向前迈了一步,但现在卡住了,谁能看到我看不到的东西。

标签: javascriptarraysfirebasegoogle-cloud-firestore

解决方案


您可以通过多种方式开发应用程序以将 Firestore 中的数据返回到数组中。通常,您只需使用 a 迭代所有数据get(),因此它们都被加载到一个数组中。例如,像下面这样一个:

let products = this.updates.collection.get()
  .then(querySnapshot => {
    products = querySnapshot.docs.map(doc => doc.data())
  })

正如此处的答案所示这将返回所有文档 -querySnapshot()执行此操作 - 并将数据保存到products数组中。

另一种方法是使用 withawait()将数据迭代到数组中。以下代码基于此处的另一个答案,以防您想检查原始答案。

const prodRef = db.collection('products');

export const getProducts = async (ids = []) => {
    let products = {};

    try {
        products = (await Promise.all(ids.map(id => prodRef.doc(id).get())))
            .filter(doc => doc.exists)
            .map(doc => ({ [doc.id]: doc.data() }))
            .reduce((acc, val) => ({ ...acc, ...val }), {});

    } catch (error) {
        console.log(`received an error in getUsers method in module \`db/products\`:`, error);
        return {};

    }

    return products;
}

虽然这些代码未经测试,但我相信它们应该可以帮助您作为开发的起点。

让我知道这些信息是否对您有帮助


推荐阅读