如何使用.net在FireStore中检查集合和文档是否存在以及是否创建具有特定ID的集合和文档

时间:2018-08-03 13:27:16

标签: c# .net google-cloud-firestore

在Firestore中,您如何检查是否存在集合和文档,如果不存在,则如何使用.NET创建具有特定ID的新集合和文档?

1 个答案:

答案 0 :(得分:1)

对于每个this answer for a node based question,将自动创建该集合,但是即使如此,如何执行此操作也不是一件容易的事,尤其是在.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;
        }