如何将具有动态ID的文档保存到Cloud Firestore?不断变化 [英] How to save a document with a dynamic id into Cloud Firestore? Always changing

查看:67
本文介绍了如何将具有动态ID的文档保存到Cloud Firestore?不断变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Cloud Firestore用作数据库
这是我网页上的表单代码,该表单代码在Cloud Firestore集合中创建了一个名为 esequiz的新文档。那么,如何以始终将数据库中的文档数加1的方式对其进行编码?并且还限制了数据库内部文档数量的限制

I am using Cloud Firestore as my database This is my form codes on my webpage that creates a new document into my Cloud Firestore collection called "esequiz". So how do I code it in such a way that it always plus 1 to the number of documents there are in the database? And also set a limit to having the amount of documents inside the database

form.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('esequiz').add({
    question: form.question.value,
    right: form.right.value,
    wrong: form.wrong.value
});
form.question.value = '';
form.right.value = '';
form.wrong.value = '';
});

当前有效,但会显示为自动生成的ID。如何像我目前的文件一样,从数字上继续下去?当我保存时,我希望它读取当前的最后一个文档ID,或者简单地计算文档的数量,然后+ 1

It currently works but it will show up as an auto generated ID. How do I make it carry on from the numbers, like as my current documents? When i save I would like it to read the current last document id, OR simply count the number of documents, then just + 1

Andrei Cusnir的见解不支持在Cloud Firestore中对文档进行计数。

Insight from Andrei Cusnir, counting documents in Cloud Firestore is not supported.

现在,我正在尝试Andrei的方法2,以降序方式查询文档顺序,然后使用.limit仅检索第一个。

Now I am trying Andrei's approach 2, to query documents in descending order, then using .limit to retrieve the first one only.

更新

form.addEventListener('submit', (e) => {
e.preventDefault();
let query = db.collection('esequiz');
let getvalue = query.orderBy('id', 'desc').limit(1).get();
let newvalue = getvalue + 1;
db.collection('esequiz').doc(newvalue).set({
    question: form.question.value,
    right: form.right.value,
    wrong: form.wrong.value
});
form.question.value = '';
form.right.value = '';
form.wrong.value = '';
});

没有更多错误,而是下面的代码返回[object Promise]

No more error, but instead, the code below returns [object Promise]


let getvalue = query.orderBy('id','desc')。limit(1).get();

let getvalue = query.orderBy('id', 'desc').limit(1).get();

因此,当我保存表单时,它另存为[object Promise] 1,我不知道为什么会这样。有人可以建议我如何返回文档ID值,而不是[object Promise]

So when my form saves, it saves as [object Promise]1, which I don't know why it is like this. Can someone advise me on how to return the document id value instead of [object Promise]

我认为这是因为我确实指定了将文档ID用作值,我该怎么办?

I think it is because I did specify to pull the document id as the value, how do I do so?

已更新:最终解决方案

使用Andrei的代码,这里是最终的代码。

Played around with the codes from Andrei, and here are the final codes that works. Much thanks to Andrei!

let query = db.collection('esequiz');
//let getvalue = query.orderBy('id', 'desc').limit(1).get();
//let newvalue = getvalue + 1;    
query.orderBy('id', 'desc').limit(1).get().then(querySnapshot => {
    querySnapshot.forEach(documentSnapshot => {
        var newID = documentSnapshot.id;
        console.log(`Found document at ${documentSnapshot.ref.path}`);
        console.log(`Document's ID: ${documentSnapshot.id}`);
        var newvalue = parseInt(newID, 10) + 1;
        var ToString = ""+ newvalue;
        db.collection('esequiz').doc(ToString).set({
            id: newvalue,
            question: form.question.value,
            right: form.right.value,
            wrong: form.wrong.value
        });
    });
    });


推荐答案

如果我正确理解您正在向云中添加数据Firestore和每个新文档都将具有一个增量编号。

If I understood correctly you are adding data to the Cloud Firestore and each new document will have as name an incremental number.

如果您查询所有文档,然后计算其中有多少文档,那么随着数据库的增加,您最终将要读取许多文档。别忘了Cloud Firestore是按文件读写收费的,因此,如果您有100个文件,并且要添加ID为101的新文件,那么先读取所有文件然后计算它们的方法将使您花费很多100次读取,然后1次写入。下次将花费您101次读取和1次写入。

If you query all the documents and then count how many are of them, then you are going to end up with many document reads as the database increases. Don't forget that Cloud Firestore is charging per document Read and Write, therefore if you have 100 documents and you want to add new document with ID: 101, then with the approach of first reading all of them and then counting them will cost you 100 Reads and then 1 Write. The next time it will cost you 101 Reads and 1 Write. And it will go on as your database increases.

我看到的方法来自两种不同的方法:

The way I see is from two different approaches:

您可以有一个文档,其中包含数据库的所有信息以及别名。

You can have a single document that will hold all the information of the database and what the next name should be.

例如

The structure of the database:
esequiz:
        0: 
          last_document: 2
        1: 
          question: "What is 3+3?
          right: "6"
          wrong: "0"
        2: 
          question: "What is 2+3?
          right: "5"
          wrong: "0"

该过程将如下所示:


  1. 读取文档 / esequiz / 0 计为1读

  2. 创建具有以下ID的新文档: last_document + 1 算作1 WRITE

  3. 更新包含该信息的文档: last_document = 3; 算作1 WRITE

  1. Read document "/esequiz/0" Counts as 1 READ
  2. Create new document with ID: last_document + 1 Counts as 1 WRITE
  3. Update the document that holds the information: last_document = 3; Counts as 1 WRITE

这种方法花费了1 READ和2写到数据库。

This approach cost you 1 READ and 2 WRITES to the database.

您只能从数据库中加载最后一个文档并获取其ID。

You can load only the last document from the database and get it's ID.

例如

The structure of the database (Same as before, but without the additional doc):
esequiz:
        1: 
          question: "What is 3+3?
          right: "6"
          wrong: "0"
        2: 
          question: "What is 2+3?
          right: "5"
          wrong: "0"

该过程将如下所示:


  1. 使用使用Cloud Firestore 文档订购和限制数据。因此,您可以将 direction = firestore.Query.DESCENDING limit(1)组合使用文献。 计数为1读

  2. 现在您知道已加载文档的ID,因此可以创建具有ID的新文档:它将使用已加载的值并将其增加1. 算为1 WRITE

  1. Read the last document using the approach described in Order and limit data with Cloud Firestore documentation. So you can use direction=firestore.Query.DESCENDING with combination of limit(1) which will give you the last document. Counts as 1 READ
  2. Now you know the ID of the loaded document so you can create new document with ID: that will use the loaded value and increase it by 1. Counts as 1 WRITE

这种方法花费了您1 READ并总共1 WRITE到数据库。

This approach cost you 1 READ and 1 WRITE in total to the database.

我希望此信息对您有所帮助,并且可以解决您的问题。目前不支持Cloud Firestore中的文档计数。

I hope that this information was helpful and it resolves your issue. Currently counting documents in Cloud Firestore is not supported.

更新

为了使排序有效,您还需要将ID包含在文档的字段中,以便您可以基于该ID进行订购。我已经测试了下面的示例,并且对我有用:

In order for the sorting to work, you will also have to include the id as a filed of the document that so you can be able to order based on it. I have tested the following example and it is working for me:

数据库结构:

esequiz:
        1: 
          id: 1
          question: "What is 3+3?
          right: "6"
          wrong: "0"
        2: 
          id:2
          question: "What is 2+3?
          right: "5"
          wrong: "0"

您可以

现在,您可以查询所有文档并根据所提交的文档进行订购。同时,您只能从查询中检索最后一个文档:

Now you can query all the documents and order based on that filed. At the same time you can only retrieve the last document from the query:

const {Firestore} = require('@google-cloud/firestore');
const firestore = new Firestore();

async function getLastDocument(){

    let query = firestore.collection('esequiz');

    query.orderBy('id', 'desc').limit(1).get().then(querySnapshot => {
    querySnapshot.forEach(documentSnapshot => {
        console.log(`Found document at ${documentSnapshot.ref.path}`);
        console.log(`Document's ID: ${documentSnapshot.id}`);
    });
    });

}

OUTPUT:
Found document at esequiz/2
Document's ID: 2

然后您可以获取ID并将其增加1,以生成新文档的名称!

Then you can take the ID and increase it by 1 to generate the name for your new document!

更新2

因此,最初的问题是关于如何使用ID为增量的文档在Cloud Firestore中存储数据当您遇到在项目中设置Firestore的问题时。不幸的是,应该在另一个Stackoverflow帖子中讨论新提出的问题,因为它们与为文档增加ID的逻辑无关,并且最好每个问题保留一个问题,以便为正在寻找的成员提供更好的社区支持对于特定问题的解决方案。因此,在本文中,我将尝试帮助您执行一个简单的Node.js脚本并解决最初的问题,该问题将使用增量ID存储到Cloud Firestore文档中。其他有关如何在项目中进行设置以及如何在页面中具有此功能的问题,都应该在其他问题中解决,在该问题中,您还需要提供尽可能多的有关所使用的框架(项目设置)的信息。等等。

So, the initial question is about "How to store data in the Cloud Firestore with documents having incremental ID", at the moment you are facing issues of setting up Firestore with you project. Unfortunately, the new raised questions should be discussed in another Stackoverflow post as they have nothing to do with the logic of having incremental IDs for the document and it is better to keep one issue per question, to give better community support for members that are looking for a solution about particular issues. Therefore, I will try to help you, in this post, to execute a simple Node.js script and resolve the initial issue, which is storing to Cloud Firestore documents with incremental IDs. Everything else, on how to setup this in your project and how to have this function in your page, should be addressed in additional question, where you also will need to provide as much information as possible about the Framework you are using, the project setup etc.

因此,让一个简单的app.js与上述逻辑一起工作:

So, lets make a simple app.js work with the logic described above:


  1. 由于您已经在使用Cloud Firestore,这意味着您已经在使用Google Cloud Platform项目(Firestore依赖于该项目)并且已经启用了正确的API。 否则它将不起作用

  2. 本教程中的指南是 Cloud Firestore:Node.js客户端文档。它将帮助您了解可与Firestore Node.js API一起使用的所有方法。您可以找到有用的链接来添加,阅读,查询文档以及更多操作。 (我将在此步骤的稍后部分中发布整个工作代码。我只是共享了链接,因此您知道在哪里可以找到其他功能

  3. 转到 Google云控制台仪表板页面。您应该使用设置有Firestore数据库的项目的Google帐户登录。

  4. 在右上角,您应该会看到4个按钮和个人资料图片。第一个按钮是激活Cloud Shell 。这将在页面底部打开一个终端,该终端已安装linux OS和Google Cloud SDK。在那里,您可以与GCP项目中的资源进行交互,并在本地测试代码,然后再在项目中使用它。

  5. 单击该按钮后,您会注意到终端将在您的页面。

  6. 为确保您已正确通过身份验证,我们将设置项目并再次对帐户进行身份验证,即使默认情况下已完成也是如此。因此,首先执行 $ gcloud auth login

  7. 在提示的问题上键入 Y 然后按Enter键。

  8. 单击生成的链接并在提示窗口上对您的帐户进行身份验证

  9. 将生成的字符串复制回终端,然后按Enter键。现在,您应该已经通过正确的身份验证。

  10. 然后使用以下命令设置包含Cloud Firestore数据库的项目: $ gcloud config set project PROJECT_ID 。现在您可以构建一个简单的app.js脚本并执行它。

  11. 创建一个新的app.js文件: nano app.js

  12. 在内部粘贴我的代码示例,可以在此 GitHub链接。它包含一个完整的示例,并包含许多解释每个部分的注释,因此最好通过GitHub链接共享它,而不是在此处粘贴。无需进行任何修改,此代码将完全执行您要执行的操作。我已经对其进行自我测试,并且可以正常工作。

  13. 执行脚本为: node app.js

  14. 这会给您以下错误:

  1. Since you have Cloud Firestore already working, this means that you already have Google Cloud Platform project (where the Firestore relies) and the proper APIs already enabled. Otherwise it wouldn't be working.
  2. Your guide in this tutorial is the Cloud Firestore: Node.js Client documentation. It will help you to understand all the methods you can use with the Firestore Node.js API. You can find helpful links for adding, reading, querying documents and many more operations. (I will post entire working code later in this steps. I just shared the link so you know where to look for additional features)
  3. Go to Google Cloud Console Dashboard page. You should login with your Google account where your project with the Firestore database is setup.
  4. On top right corner you should see 4 buttons and your profile picture. The first button is the Activate Cloud Shell. This will open a terminal on the bottom of the page with linux OS and Google Cloud SDK already install. There you can interact with your resources within GCP projects and test your code locally before using it in your projects.
  5. After clicking that button, you will notice that the terminal will open in the bottom of your page.
  6. To make sure that you are properly authenticated we will set up the project and authenticate the account again, even if it is already done by default. So first execute $ gcloud auth login
  7. On the prompted question type Y and hit enter
  8. Click on the generated link and authenticate your account on the prompted window
  9. Copy the generated string back to the terminal and hit enter. Now you should be properly authenticated.
  10. Then setup the project that contains Cloud Firestore database with the following command: $ gcloud config set project PROJECT_ID. Now you are ready to build a simple app.js script and execute it.
  11. Create a new app.js file: nano app.js
  12. Inside paste my code example that can be found in this GitHub link. It contains fully working example and many comments explaining each part therefore it is better that it is shared through GitHub link and not pasted here. Without doing any modifications, this code will execute exactly what you are trying to do. I have tested it my self and it is working.
  13. Execute the script as: node app.js
  14. This will give you the following error:

错误:找不到模块'@ google-cloud / firestore'

Error: Cannot find module '@google-cloud/firestore'


由于我们正在导入库 @ google-cloud / firestore ,但尚未安装。

Since we are importing the library @google-cloud/firestore but haven't installed it yet.


  1. 安装 @ google-cloud / firestore 库,如下所示: $ npm i @ google-cloud / firestore 。在 DOC 中描述。

  2. 再次执行脚本: $节点app.js

  3. 您应该看到例如 ID为3的文档被写入。

  4. 如果再次执行,应该看到例如 ID为4的文档被写入。

  1. Install @google-cloud/firestore library as follows: $ npm i @google-cloud/firestore. Described in DOC.
  2. Execute the script again: $ node app.js.
  3. You should see e.g. Document with ID: 3 is written.
  4. If you execute again, you should see e.g. Document with ID: 4 is written.

所有这些更改都应出现在您的Cloud Firestore数据库。如您所见,它正在加载最后一个文档的ID,它正在创建一个新ID,然后使用给定的参数创建一个新文档,同时使用新生成的ID作为文档名称。这正是最初的问题所在。

All those changes should appear in your Cloud Firestore database as well. As you can see it is loading the ID of the last document, it is creating a new ID and then it creates a new document with the given arguments, while using the new generated ID as document name. This is exactly what the initial issue was about.

因此,我已经与您分享了完整的代码,该代码可以正常工作,并且完全可以满足您的要求。不幸的是,其他新提出的问题应在另一个Stackoverflow帖子中解决,因为它们与最初的问题如何创建具有增量ID的文档无关。我建议您按照以下步骤操作并使用一个有效的示例,然后尝试对您的项目实施逻辑。但是,如果您仍在如何在项目中设置Firestore方面遇到任何问题,则可以提出另一个问题。之后,您可以结合使用这两种解决方案,并且您将可以使用该应用程序!

So I have shared with you the full code that works and does exactly what you are trying to do. Unfortunately, the other newly raised issues, should be addressed in another Stackoverflow post, as they have nothing to do with the initial issue, which is "How to create documents with incremental ID". I recommend you to follow the steps and have a working example and then try to implement the logic to your project. However, if you are still facing any issues with how to setup Firestore in your project then you can ask another question. After that you can combine both solutions and you will have working app!

祝您好运!

这篇关于如何将具有动态ID的文档保存到Cloud Firestore?不断变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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