Reactjs 读取时更新FireStore文档

Reactjs 读取时更新FireStore文档,reactjs,firebase,google-cloud-firestore,Reactjs,Firebase,Google Cloud Firestore,我正在使用React和Firestore创建一个类似博客的网站。每篇文章都作为单独的文档存储在文章集合中 文档结构如下所示: --Posts --Post1 --title --body --views --likes --Post2 --title --body --views --likes 每当

我正在使用React和Firestore创建一个类似博客的网站。每篇文章都作为单独的文档存储在文章集合中

文档结构如下所示:

--Posts
     --Post1
           --title
           --body
           --views
           --likes
     --Post2
           --title
           --body
           --views
           --likes

每当有人查看帖子时,我都要更新视图。在Firestore中实现这一点的最佳方法是什么。

对于许多情况,您可以直接使用。但是,由于您要递增计数器,因此当多个用户试图同时递增计数器时,还应使用计数器来防止竞争条件:

// Create a reference to the post.
const postRef = db.collection('Posts').doc('<postId>');

return db.runTransaction(function(transaction) {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(postRef).then(function(post) {
      if (!post.exists) {
        throw new Error('Post does not exist!');
      }

      const newViews = post.data().views + 1;
      transaction.update(postRef, { views: newViews });
    });
}).then(function() {
    console.log('Transaction successfully committed!');
}).catch(function(error) {
    console.log('Transaction failed: ', error);
});
//创建对文章的引用。
const postRef=db.collection('Posts').doc('');
返回db.runTransaction(函数(事务){
//如果存在冲突,此代码可能会重新运行多次。
返回事务.get(postRef).then(函数(post){
如果(!post.exists){
抛出新错误('Post不存在!');
}
const newViews=post.data().views+1;
update(postRef,{views:newViews});
});
}).然后(函数(){
console.log('Transaction successfully committed!');
}).catch(函数(错误){
console.log('事务失败:',错误);
});

对于许多情况,您可以直接使用。但是,由于您要递增计数器,因此当多个用户试图同时递增计数器时,还应使用计数器来防止竞争条件:

// Create a reference to the post.
const postRef = db.collection('Posts').doc('<postId>');

return db.runTransaction(function(transaction) {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(postRef).then(function(post) {
      if (!post.exists) {
        throw new Error('Post does not exist!');
      }

      const newViews = post.data().views + 1;
      transaction.update(postRef, { views: newViews });
    });
}).then(function() {
    console.log('Transaction successfully committed!');
}).catch(function(error) {
    console.log('Transaction failed: ', error);
});
//创建对文章的引用。
const postRef=db.collection('Posts').doc('');
返回db.runTransaction(函数(事务){
//如果存在冲突,此代码可能会重新运行多次。
返回事务.get(postRef).then(函数(post){
如果(!post.exists){
抛出新错误('Post不存在!');
}
const newViews=post.data().views+1;
update(postRef,{views:newViews});
});
}).然后(函数(){
console.log('Transaction successfully committed!');
}).catch(函数(错误){
console.log('事务失败:',错误);
});