Firestore unique index or unique constraint?

前端 未结 3 1868
悲哀的现实
悲哀的现实 2020-11-30 07:53

Is it possible in Firestore to define an index with a unique constraint? If not, how is it possible to enforce uniqueness on a document field (without using document ID)?

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 08:29

    Based on the documentation from this section https://cloud.google.com/firestore/docs/manage-data/add-data#set_a_document

    You can simply add a custom identifier when adding document object to a collection as shown below:

    const data = {
      name: 'Los Angeles',
      state: 'CA',
      country: 'USA'
    };
    
    // Add a new document in collection "cities" with ID 'LA'
    const res = await db.collection('cities').doc('LA').set(data);
    

    Using this https://cloud.google.com/firestore/docs/manage-data/add-data#node.js_4 as a reference when you use set as a method on your collection you can be able to specify an id for such document when you need to auto-generate an id you simply use the add method on your collection

提交回复
热议问题