【问题标题】:How to add multiple fields in a document in firebase?如何在firebase的文档中添加多个字段?
【发布时间】:2020-08-06 10:33:30
【问题描述】:

我想将某些设备的设备令牌保存在不同字段的单个文档中。

这是我的代码,


StreamBuilder(
              stream: stream,
              builder: (BuildContext context,
                  AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
                if (snapshots.connectionState == ConnectionState.active &&
                    snapshots.hasData) {
                  return Expanded(
                    child: ListView.builder(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemCount: snapshots.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        DocumentSnapshot doc = snapshots.data[index];
                        Map location = doc.data;
                        String fieldname = 'f$index';

                        var dtoken = location['deviceToken'];

                       
                         

                          _firestore.collection('deviceTokens').add({
                            fieldname: dtoken,
                          });
                       
                     
              

                       
                        return Text(
                          "xyz",
                        );
                      },
                    ),
                  );
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),

我想在一个文档中存储多个 deviceToken。

为了更清楚,

当此代码运行时,我只想在我的数据库中创建一个文档,该文档在多个字段中具有设备令牌,例如,

在单个文档中-

f1:"第一个设备令牌",

f2:"第二个设备令牌",

fn:"第 n 个设备令牌"

但是这段代码创建了许多具有不同设备令牌的文档(每个文档1个字段)。

请帮忙

更新代码

StreamBuilder(
              stream: stream,
              builder: (BuildContext context,
                  AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
                if (snapshots.connectionState == ConnectionState.active &&
                    snapshots.hasData) {
                  return Expanded(
                    child: ListView.builder(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemCount: snapshots.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        var docid;

                        if (index == 0) {
                         _firestore
                              .collection('devicetokens')
                              .add({}).then((value) => docid = value);
                        }
                        DocumentSnapshot doc = snapshots.data[index];
                        Map location = doc.data;
                        String fieldname = 'f$index';


                        var dtoken = location['deviceToken'];

                        DocumentReference docss =
                            _firestore.collection("devicetokens").document(docid);
                        docss.setData({
                          fieldname: dtoken,
                        });
                        
                       

                       
                        return Text(
                          "xyz",
                        );
                      },
                    ),
                  );
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),

【问题讨论】:

  • 你应该先得到一个文件,然后再写给它
  • 我该怎么做,你能解释一下,这真的很有帮助
  • 如果我的回答有用请采纳,否则请告诉我
  • 是否有任何理由需要每个令牌位于不同的字段中?这似乎是不必要的复杂。您可以改为将令牌推送到单个数组字段中。
  • @DougStevenson 我想要的只是触发我的云功能,以向我在该新创建文档的字段中拥有的那些设备令牌发送通知(我将在发送通知后删除文档)。还有其他方法可以实现吗?

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

替换这个:

_firestore.collection('deviceTokens').add({
  fieldname: dtoken,
});

这样的:

  DocumentReference doc = _firestore.collection(deviceTokens).document();
  doc.setData({
    "f1" : "1st device token",
    "f2" : "2nd device token",
    "fn" :"nth device token",
  });


编辑:这是您可以做到的一种方法。使用.document()方法同步获取docid。
不要使用.collection.add() 来获取 docID,因为它是异步的,这意味着它将为 null,直到将来解析(直到服务器返回 docID)。您需要已经拥有 docID 才能使用 setData 写入它。

这应该可行。或者至少让您顺利找到解决方案。

StreamBuilder(
              stream: stream,
              builder: (BuildContext context,
                  AsyncSnapshot<List<DocumentSnapshot>> snapshots) {
                if (snapshots.connectionState == ConnectionState.active &&
                    snapshots.hasData) {

                    //This gets you a doc ID synchronously
                    DocumentReference docid = _firestore.collection(deviceTokens).document();

                  return Expanded(
                    child: ListView.builder(
                      scrollDirection: Axis.vertical,
                      shrinkWrap: true,
                      itemCount: snapshots.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        

                        DocumentSnapshot doc = snapshots.data[index];
                        Map location = doc.data;
                        String fieldname = 'f$index';


                        var dtoken = location['deviceToken'];    

                        _firestore.collection("devicetokens")
                        .document(docid.documentID)
                        .setData({
                          fieldname: dtoken,
                        });
                        
                       

                       
                        return Text(
                          "xyz",
                        );
                      },
                    ),
                  );
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),

【讨论】:

  • 它创建了 3 个文档
  • 我希望 "f1",f2" 是动态的,这样对于 "n" 个设备令牌,它可以在同一文档中创建 "n" 个字段
  • 您可以使它们动态化。只需将它们替换为变量名即可。它们必须是字符串。
  • 它不会创建 3 个文档。 `doc.setData 每次调用都会写入一个文档。
  • 嘿!谢谢,这也对我有用,我做了一些改变:)
猜你喜欢
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 2019-06-16
  • 1970-01-01
相关资源
最近更新 更多