javascript Firestore如何获取集合的最后一个文档并添加新的递增id?

gijlo24d  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(118)

我可能犯了一个错误,为我的事件集合中的文档自动生成id。我为生成的事件添加了eventId,并手动为每个事件分配了eventId。
我能以某种方式获得最后一个文档及其eventId,并添加新文档,使最后一个文档的eventId增加1。
或者我应该删除自动生成的基于ID的事件,并创建新的非自动生成的ID?
GitHub:https://github.com/Verthon/event-app
我已经在netlify上发布了工作的React.js应用程序:https://eventooo.netlify.com/
它是如何工作的:

  • 我为事件集合中的每个虚拟事件添加了唯一的eventId,
  • 基于这个唯一的eventId,我创建了指向特定单个Event.js的链接,
  • 用户可以在/create-event中创建提供信息的事件,
  • 一旦有人正在创建一个事件,我想添加事件到事件集合与增量id,我已经添加了7个事件内创建的控制台,所以下一步应该有id=7,可能像event 1,event 2...与自动增量
  • 在users集合中,我存储来自auth的currentUser.uid和用户提供的主机名
Event Creator

submitEvent = (e) => {
    e.preventDefault();
    const eventRef = this.props.firebase.db.collection("events").doc();
    eventRef.set({
      title: this.state.title,
      host: this.state.host,
      localization: this.state.localization,
      description: this.state.description,
      category: this.state.category,
      day: this.state.day,
      hour: this.state.hour,
      featuredImage: this.state.imageUrl,
      uid: this.props.firebase.auth.currentUser.uid
    });

    const citiesRef = this.props.firebase.db.collection("cities").where("city", "==", this.state.localization);
    const cityRef = this.props.firebase.db.collection("cities").doc();
    citiesRef.get()
      .then(querySnapshot => {
        if(querySnapshot.exists){
          console.log("exist");
          return
        }else{
          cityRef.set({
            city: this.state.localization,
          })
        }
      });
    const userRef = this.props.firebase.db.collection("users").doc();
    userRef.set({
      user: this.state.host,
      uid: this.props.firebase.auth.currentUser.uid
    });

谢谢你

amrnrhlw

amrnrhlw1#

我理解你希望你的eventId值来自一个数字序列。这种需求的最佳方法是使用分布式计数器,如文档中所述:https://firebase.google.com/docs/firestore/solutions/counters
我不知道您使用的是哪种语言,但我将本文档中的三个函数的JavaScript代码粘贴在下面,并编写了将生成序列号的代码,您可以使用该序列号创建文档。

var db = firebase.firestore();

  //From the Firebase documentation

  function createCounter(ref, num_shards) {
    var batch = db.batch();

    // Initialize the counter document
    batch.set(ref, { num_shards: num_shards });

    // Initialize each shard with count=0
    for (let i = 0; i < num_shards; i++) {
      let shardRef = ref.collection('shards').doc(i.toString());
      batch.set(shardRef, { count: 0 });
    }

    // Commit the write batch
    return batch.commit();
  }

  function incrementCounter(db, ref, num_shards) {
    // Select a shard of the counter at random
    const shard_id = Math.floor(Math.random() * num_shards).toString();
    const shard_ref = ref.collection('shards').doc(shard_id);

    // Update count
    return shard_ref.update(
      'count',
      firebase.firestore.FieldValue.increment(1)
    );
  }

  function getCount(ref) {
    // Sum the count of each shard in the subcollection
    return ref
      .collection('shards')
      .get()
      .then(snapshot => {
        let total_count = 0;
        snapshot.forEach(doc => {
          total_count += doc.data().count;
        });

        return total_count;
      });
  }

  //Your code

  var ref = firebase
    .firestore()
    .collection('counters')
    .doc('1');

  var num_shards = 2  //Adapt as required, read the doc

  //Initialize the counter bay calling ONCE the createCounter() method

  createCounter(ref, num_shards);

  //Then, when you want to create a new number and a new doc you do

  incrementCounter(db, ref, num_shards)
    .then(() => {
      return getCount(ref);
    })
    .then(count => {
      console.log(count);
      //Here you get the new number form the sequence
      //And you use it to create a doc
      db.collection("events").doc(count.toString()).set({
         category: "education",
         //.... 
      })
    });

如果没有关于功能需求的详细信息,很难说使用序列中的数字作为文档的uid或作为文档中的字段值之间是否有区别。这取决于您可能对该集合进行的查询。

相关问题