How to add document Id in the document in firestore database in flutter application

坚强是说给别人听的谎言 提交于 2020-07-31 06:10:48

问题


I am using below code to add document in firestore collection in a flutter application. I am not getting an idea that on how to add the document id in the document. Please guide me

    Firestore.instance.collection("posts1").add({
                    //"id": "currentUser.user.uid",
                    "postTitle": posttitle.text,
                    "postcategory": selectedCategory,
                    "post_id":documentId,
                      })
                      .then((result) =>
                  {print("success")}

回答1:


Use document() with no arguments to first generate a reference to a document with a random ID, then use setData() to create it and add the documentID as part of the new document:

DocumentReference ref = Firestore.instance.collection("posts1").document();
ref.setData({
    "post_id": ref.documentID,
    // ... add more fields here
})



回答2:


DocumentReference docRef = await Firestore.instance.collection("products").add({

 'description': product.description,
 'imageUrl': product.imageUrl,
 'price': product.price,
});
final newProduct = Product(
 title: product.title,
 description: product.description,
 price: product.price,
 imageUrl: product.imageUrl,
 id:docRef.documentID,
);

_items.add(newProduct);


来源:https://stackoverflow.com/questions/62008906/how-to-add-document-id-in-the-document-in-firestore-database-in-flutter-applicat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!