在Firebase Flutter中创建新文档后立即获取文档ID。

huangapple go评论70阅读模式
英文:

Obtain Document ID immediately after you create a new document with Set in Firebase Flutter

问题

我需要获取我刚创建的文档的文档ID。

我使用以下代码创建新文档:

db.collection('Pack').doc().set({
    'userId': userID,
    'packName': newPackNameController.text.trim(),
    'description': newPackDescriptionController.text.trim(),
    //todo: 需要计算新重量或从此包中获取...
    'totalWeight': '0.0',
    'weightFormat': weightFormat,
});

接下来,我需要文档ID。

根据另一个Stack Overflow的问题,我尝试了以下方法:

DocumentReference docRef = await Firestore.instance.collection('gameLevels').add(map);
print(docRef.documentID);

但这是用于添加集合而不是文档,我无法使用相同的代码来获取文档的ID。

英文:

In my app I need to get the document ID for a document I just created.

I am creating the new document with:

db.collection('Pack').doc().set({
                    'userId': userID,
                    'packName': newPackNameController.text.trim(),
                    'description': newPackDescriptionController.text.trim(),
                    //todo: need to calculate new weight or grab from this pack...
                    'totalWeight': '0.0',
                    'weightFormat': weightFormat,
                  });

Next I need to document ID.

I tried this based on another stack overflow question:

DocumentReference docRef = await 
Firestore.instance.collection('gameLevels').add(map);
print(docRef.documentID);

But that was for adding a collection and not a document and I could not get the same code to work with a document.

答案1

得分: 1

The call to doc() is a pure client-side operation, so you can split it from the set():

var ref = db.collection('Pack').doc();
print(ref.id);
ref.set({
  'userId': userID,
  'packName': newPackNameController.text.trim(),
  'description': newPackDescriptionController.text.trim(),
  //todo: need to calculate new weight or grab from this pack...
  'totalWeight': '0.0',
  'weightFormat': weightFormat,
});

Also see the last code sample in the documentation on adding a document.

英文:

The call to doc() is a pure client-side operation, so you can split it from the set():

var ref = db.collection('Pack').doc();
print(ref.id);
ref.set({
  'userId': userID,
  'packName': newPackNameController.text.trim(),
  'description': newPackDescriptionController.text.trim(),
  //todo: need to calculate new weight or grab from this pack...
  'totalWeight': '0.0',
  'weightFormat': weightFormat,
});

Also see the last code sample in the documentation on adding a document.

huangapple
  • 本文由 发表于 2023年3月23日 08:18:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75818303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定