C#/Firebase

C# : Firebase 사용하기 - 05 (Firebase 데이터 수정)

Half-Dev 2021. 1. 2. 13:51

안녕하세요.

하프개발자 입니다.

 

이번에는 Firebase 데이터 수정을 알아보도록 하겠습니다.

 


Firebase에서 Testing 컬렉션과 docs1이라는 문서를 생성해주세요.

 


Part 1. SetAsync 사용

SetAsync를 사용하게 되면, 기존에 있던 필드들은 사라지고 설정한 필드와 값으로 바뀌게 됩니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
async void Replace_A_Document_Deleting_All_Previous_Fields()
{
    DocumentReference docref = db.Collection("Testing").Document("docs1");
    Dictionary<stringobject> data = new Dictionary<stringobject>()
    {
        {"name""Jinwon" },
        {"web""naver.com" }
    };
    DocumentSnapshot snap = await docref.GetSnapshotAsync();
    if (snap.Exists)
    {
        await docref.SetAsync(data);
    }
}
cs

 

 

 

 

Part 2. UpdateAsync 사용

UpdateAsync는 SetAsync와는 달리 필드값을 지우지 않고 업데이트만 수행하는 메소드 입니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
async void Update_Specific_Fields_or_Add_New_Fields_Within_A_Document()
{
    DocumentReference docref = db.Collection("Testing").Document("docs1");
    Dictionary<stringobject> data = new Dictionary<stringobject>()
    {
        {"name""Kim Jinwon" },
        {"web""daum.com" },
        {"newField"123 }
    };
    DocumentSnapshot snap = await docref.GetSnapshotAsync();
    if (snap.Exists)
    {
        await docref.UpdateAsync(data);
    }
}
cs

 

 

 

 

Part 3. List Update

여기서부터는 부가적인 내용이니, Part1 과 Part2만 해도 충분하다 생각하시면 넘어가셔도 됩니다.

 

필드값은 업데이트를 했는데, 리스트의 경우 어떻게 업데이트를 해야할까?

이를 위해서는  .을 사용해서 해당 리스트에 접근을 합니다.

 

예를들어 리스트의 이름이 MyList 이고 MyList안의 필드값이 Name 일 경우 MyList.Name 으로 접근해주시면 됩니다.

 

저는 List가 생성되었던 Add_ListOfObjets 컬렉션을 사용하도록 하겠습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
async void Update_List_Elements_or_Nested_Elements()
{
    DocumentReference docref = db.Collection("Add_ListOfObjects").Document("myDoc");
    Dictionary<stringobject> data = new Dictionary<stringobject>()
    {
        {"MyList.PhoneNumber""010-0000-0000" }
    };
    DocumentSnapshot snap = await docref.GetSnapshotAsync();
    if (snap.Exists)
    {
        await docref.UpdateAsync(data);
    }
}
cs

 

 

 

 

 

Part 4. Array Update

Array또한 전에 만들어 놓았던 Add_Array 컬렉션을 사용하도록 하겠습니다.

아래의 결과를 보았을 때, 있는것은 그대로 없는것은 추가가 되는것을 볼 수 있습니다.

 

1
2
3
4
5
6
7
8
9
async void Update_Array_Elements()
{
    DocumentReference docref = db.Collection("Add_Aray").Document("myDoc");
    DocumentSnapshot snap = await docref.GetSnapshotAsync();
    if (snap.Exists)
    {
        await docref.UpdateAsync("My Array", FieldValue.ArrayUnion(123"abcd"456));
    }
}
cs

 

 


제가 준비한 내용은 여기까지 입니다.

다음글에서 뵙도록 하겠습니다.

 

해당 코드는 저의 깃허브에서도 볼 수 있습니다.

전체 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Cloud.Firestore;
 
namespace CsFirebaseBlog
{
    public partial class Form1 : Form
    {
        FirestoreDb db;
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Replace_A_Document_Deleting_All_Previous_Fields();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Update_Specific_Fields_or_Add_New_Fields_Within_A_Document();
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            Update_List_Elements_or_Nested_Elements();
        }
 
        private void button4_Click(object sender, EventArgs e)
        {
            Update_Array_Elements();
        }
        private void Form1_Load(object sender, EventArgs e)
        {  
            string path = AppDomain.CurrentDomain.BaseDirectory + @"cs-firebase-blog-firebase-adminsdk-18cwe-b5971a4787.json";
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
 
            db = FirestoreDb.Create("cs-firebase-blog");
        }
 
        async void Replace_A_Document_Deleting_All_Previous_Fields()
        {
            DocumentReference docref = db.Collection("Testing").Document("docs1");
            Dictionary<stringobject> data = new Dictionary<stringobject>()
            {
                {"name""Jinwon" },
                {"web""naver.com" }
            };
            DocumentSnapshot snap = await docref.GetSnapshotAsync();
            if (snap.Exists)
            {
                await docref.SetAsync(data);
            }
        }
 
        async void Update_Specific_Fields_or_Add_New_Fields_Within_A_Document()
        {
            DocumentReference docref = db.Collection("Testing").Document("docs1");
            Dictionary<stringobject> data = new Dictionary<stringobject>()
            {
                {"name""Kim Jinwon" },
                {"web""daum.com" },
                {"newField"123 }
            };
            DocumentSnapshot snap = await docref.GetSnapshotAsync();
            if (snap.Exists)
            {
                await docref.UpdateAsync(data);
            }
        }
        async void Update_List_Elements_or_Nested_Elements()
        {
            DocumentReference docref = db.Collection("Add_ListOfObjects").Document("myDoc");
            Dictionary<stringobject> data = new Dictionary<stringobject>()
            {
                {"MyList.PhoneNumber""010-0000-0000" }
            };
            DocumentSnapshot snap = await docref.GetSnapshotAsync();
            if (snap.Exists)
            {
                await docref.UpdateAsync(data);
            }
        }
 
        async void Update_Array_Elements()
        {
            DocumentReference docref = db.Collection("Add_Aray").Document("myDoc");
            DocumentSnapshot snap = await docref.GetSnapshotAsync();
            if (snap.Exists)
            {
                await docref.UpdateAsync("My Array", FieldValue.ArrayUnion(123"abcd"456));
            }
        }
    }
}
cs