亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何檢查集合和文檔是否存在,如果不存在,則使用 .net 在 FireStore 中創建具有特定

如何檢查集合和文檔是否存在,如果不存在,則使用 .net 在 FireStore 中創建具有特定

C#
慕婉清6462132 2021-11-14 15:11:02
在 Firestore 中,您如何檢查集合和文檔是否已存在,如果不存在,則如何使用 .NET 創建具有特定 ID 的新集合和文檔?
查看完整描述

1 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

根據這個基于節點的問題的答案,將自動創建集合,但即使如此,您如何做到這一點并不容易,尤其是在 .NET 中。如果它是樹下的多個集合,則更是如此。例如,這是我們將嘗試添加的文檔類:


using Google.Cloud.Firestore;


namespace FirestoreTest.Models

{

    [FirestoreData]

    public class ClassicGame

    {

        public ClassicGame()

        {


        }


        [FirestoreProperty]

        public string title { get; set; }

        [FirestoreProperty]

        public string publisher { get; set; }

    }

}

這是一個示例函數,用于檢查集合和文檔是否存在于 PC/Games/{publisher}/{title} 中,如果不存在,則使用 gameId 作為文檔的 ID 創建它。它使用 Google.Cloud.Firestore和Google.Cloud.Firestore.V1Beta1


public async Task<bool> AddPcGame(string gameTitle, string gamePublisher, string gameId)

        {

            string publisherCollectionPath = "PC/Games/" + gamePublisher;


            //Try and get the document and check if it exists

            var document = await db.Collection(publisherCollectionPath).Document(gameId).GetSnapshotAsync();

            if (document.Exists)

            {

                //document exists, do what you want here...

                return true;

            }

             //if it doesn't exist insert it:  

            //create the object to insert

            ClassicGame newGame = new ClassicGame()

            {

                title = gameTitle,

                publisher = gamePublisher

            };

            //Notice you have to traverse the tree, going from collection to document.  

            //If you try to jump too far ahead, it doesn't seem to work. 

            //.Document(gameId).SetAsync(newGame), is what set's the document's ID and inserts the data for the document.

            CollectionReference collection = db.Collection("PC");

            var document2 = await collection.Document("Games").Collection(gamePublisher).Document(gameId).SetAsync(newGame);


            return true;

        }


查看完整回答
反對 回復 2021-11-14
  • 1 回答
  • 0 關注
  • 171 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號