在Firestore中查询和更新数据的方法

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

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
}

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

评论
  • yquo
    yquo 回复

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

    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({...});
            })
        })
    

    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(...)
    

    Note that if you are sure you have less than 500 updates to be done, you could use a set of batched writes.

    如果您知道该查询仅对应一个文档,请执行以下操作:

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

    Finally, note that if you want to increment or decrement a field in Firestore, you should use FieldValue.increment()