猿问

如何检查集合和文档是否存在,如果不存在,则使用 .net 在 FireStore 中创建具有特定

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


慕婉清6462132
浏览 139回答 1
1回答

慕盖茨4494581

根据这个基于节点的问题的答案,将自动创建集合,但即使如此,您如何做到这一点并不容易,尤其是在 .NET 中。如果它是树下的多个集合,则更是如此。例如,这是我们将尝试添加的文档类:using Google.Cloud.Firestore;namespace FirestoreTest.Models{&nbsp; &nbsp; [FirestoreData]&nbsp; &nbsp; public class ClassicGame&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public ClassicGame()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; [FirestoreProperty]&nbsp; &nbsp; &nbsp; &nbsp; public string title { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; [FirestoreProperty]&nbsp; &nbsp; &nbsp; &nbsp; public string publisher { get; set; }&nbsp; &nbsp; }}这是一个示例函数,用于检查集合和文档是否存在于 PC/Games/{publisher}/{title} 中,如果不存在,则使用 gameId 作为文档的 ID 创建它。它使用 Google.Cloud.Firestore和Google.Cloud.Firestore.V1Beta1public async Task<bool> AddPcGame(string gameTitle, string gamePublisher, string gameId)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string publisherCollectionPath = "PC/Games/" + gamePublisher;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Try and get the document and check if it exists&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var document = await db.Collection(publisherCollectionPath).Document(gameId).GetSnapshotAsync();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (document.Exists)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //document exists, do what you want here...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//if it doesn't exist insert it:&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //create the object to insert&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ClassicGame newGame = new ClassicGame()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title = gameTitle,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; publisher = gamePublisher&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Notice you have to traverse the tree, going from collection to document.&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //If you try to jump too far ahead, it doesn't seem to work.&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //.Document(gameId).SetAsync(newGame), is what set's the document's ID and inserts the data for the document.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CollectionReference collection = db.Collection("PC");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var document2 = await collection.Document("Games").Collection(gamePublisher).Document(gameId).SetAsync(newGame);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答