更新user_id与currentUser uid相同的Firestore文档 [英] Update Firestore document where user_id is same as currentUser uid
问题描述
我具有用于创建或更新客户的功能.
I have the function that I am using to create or update customer.
我能够成功写入db.我创建了一个名为user_id的字段,将currentUser uid保存到该字段中,这样我就只能读取已登录的用户文档.
I am able to successfully write to db. I created a field called user_id where I save the currentUser uid into so I can read only logged in user documents.
但是,我无法更新文档,因为我知道我可能没有正确引用文档.
However, I am unable to update the documents because I know I'm probably not referencing the document the right way.
我收到以下错误:
Flutter:错误:PlatformException(错误5,FIRFirestoreErrorDomain,否 文档更新:
flutter: Error: PlatformException(Error 5, FIRFirestoreErrorDomain, No document to update:
我在做什么错了?
这是我的以下功能:
Future createOrUpdateCustomer(Customer customer, bool isUpdating) async {
FirebaseUser user = await FirebaseAuth.instance.currentUser();
String userId = user.uid;
print('Current logged in user uid is: $userId');
CollectionReference customerRef =
await Firestore.instance.collection('customers');
if (isUpdating) {
customer.updatedAt = Timestamp.now();
customer.userId = userId;
await customerRef.document().updateData(customer.toMap());
print('updated customer with id: ${customer.id}');
print('updated customer with logged in uid: ${customer.userId}');
} else {
customer.createdAt = Timestamp.now();
DocumentReference documentReference = customerRef.document();
customer.id = documentReference.documentID;
customer.userId = userId;
print('created customer successfully with id: ${customer.id}');
await documentReference.setData(customer.toMap(), merge: true);
addCustomer(customer);
}
notifyListeners();
}
推荐答案
您正在尝试更新不存在的文档.在这一行,
You are trying to update a nonexistent document. In this line,
await customerRef.document().updateData(customer.toMap())
您正在使用随机生成的ID创建文档参考.您应该明确设置要更新的文档的id
.
You are creating a document reference with a randomly-generated id. You should explicitly set the id
of the document you're updating.
这篇关于更新user_id与currentUser uid相同的Firestore文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!