1 回答

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;
}
- 1 回答
- 0 關注
- 171 瀏覽
添加回答
舉報