在Firestore中查询和更新数据的方法 [英] Way to query and update data in Firestore

查看:25
本文介绍了在Firestore中查询和更新数据的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Stripe运行付款系统,并尝试在每次成功购买后减少Firestore中的数量字段.我可以得到文档,但是我正在努力寻找如何更新它.

I run a payment system with Stripe and am trying to decrement a quantity field in Firestore after every successful purchase. I can get the document but I'm struggling figuring out how to update it.

db.collection('products').where('id', '==', dbRef).get()
    .then(querySnapshot => {
        return querySnapshot.forEach(doc => {
            return res.json({
                data: doc.data(),
                err: err
            })
        })
    })

{
  "data": {
    "stripe": {
      "sku": "sku_xxx",
      "product": "prod_xxx"
    },
    "name": "VERSA HOODIE",
    "id": "pmz0pvfa",
    "createdBy": "Q3Vn0LLRnSWzxaeOK7V0UYbuiKF2",
    "price": "25.00",
    "quantity": 10,
    "inStock": true,
    "description": "TEST PRODUCT",
    "imageURL": "https://xxx"
  },
  "err": null
}

我尝试了诸如 doc.update({})之类的方法,但是它不起作用...预先感谢

I tried stuff like doc.update({}), but it doens't work... Thanks in advance

推荐答案

(如果您的查询总是返回一个且只有一个文档,请参见下文)

要更新查询返回的所有文档,您需要调用 update() 方法"nofollow noreferrer"> DocumentReference s ,如下:

To update all the documents returned by a query, you need to call the update() method of the DocumentReferences, as follows:

db.collection('products').where('id', '==', dbRef).get()
    .then(querySnapshot => {
        querySnapshot.forEach(doc => {
            const docRef = doc.ref;
            docRef.update({...});
        })
    })

如果您想知道所有更新何时完成,并且可能将另一个对异步方法的调用添加到Promise链中,则应使用

If you want to know when all the updates are done, and possibly add to the promise chain another call to an asynchronous method, you should use Promise.all() as follows:

db.collection('products').where('id', '==', dbRef).get()
    .then(querySnapshot => {
        const promises = [];
        querySnapshot.forEach(doc => {
            const docRef = doc.ref;
            promises.push(docRef.update({...}));
        })
        return Promise.all(promises);
    })
    .then(...)


请注意,如果您确定要完成的更新少于500个,则可以使用一组 如果您知道与查询相对应的只有一个文档,请执行以下操作:

db.collection('products').where('id', '==', dbRef).get()
    .then(querySnapshot => {
        const docRef = querySnapshot.docs[0].ref;
        return docRef.update({...});
    })


最后,请注意,如果要在Firestore中增加或减少字段,则应使用 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆