即使用户相同,也会创建新文档?

new documents gets created even though the user is the same?

我正在尝试上传多个文本字段的值,但 firestore 不断重置所有值,因此旧值消失了。我希望能够为第一个文本字段 (alOne) 设置一个值,也许稍后回来为第二个文本字段 (alTwo) 设置一个值。但在我的情况下,当设置第二个值时,第一个值从 firestore 中消失?

这是我的 post 函数

  static void createPostMonday(Post post) async{
await postsRef.document(post.authorId).setData({



  'alOne':post.alOne,
  'alTwo':post.alTwo,
  'alThree':post.alThree,
  'alFour':post.alFour,
  'alFive':post.alFive,
  'alSix':post.alSix,
  'beOne':post.beOne,
  'beTwo':post.beTwo,
  'beThree':post.beThree,
  'beFour':post.beFour,
  'beFive':post.beFive,
  'beSix':post.beSix,
  'likes': post.likes,
  'authorId': post.authorId,
  'timestamp': post.timestamp,
},merge: true);

这里是操作(提交)按钮

  _submit() async{
Post post = Post(
  authorId: Provider.of<UserData>(context, listen: false).currentUserId,
  timestamp: Timestamp.fromDate(DateTime.now()),
  alOne1: _alOne1,
  alTwo1: _alTwo1,
  alThree1: _alThree1,
  alFour1: _alFour1,
  alFive1: _alFive1,
  alSix1: _alSix1,
  beOne1: _beOne1,
  beTwo1: _beTwo1,
  beThree1: _beThree1,
  beFour1: _beFour1,
  beFive1: _beFive1,
  beSix1: _beSix1,

);
DatabaseService.createPostMonday(post);
Navigator.pop(context);

}

这是我的 2 个文本字段

   Padding(
            padding: EdgeInsets.symmetric(horizontal: 30.0),
            child: TextField(
              style: TextStyle(fontSize: 18.0),
              decoration: InputDecoration(
                labelText: 'Alternativ',
              ),
              onChanged: (input) => _alOne1 = input,
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 30.0),
            child: TextField(
              style: TextStyle(fontSize: 18.0),
              decoration: InputDecoration(
                labelText: 'Beskrivning',
              ),
              onChanged: (input) => _beOne1 = input,
            ),
          ),

您正在调用 setData,它会将文档中的所有现有数据替换为您传入的数据。

如果您想将传入的数据与文档中已有的任何现有数据合并,您有两个选择:

  1. 使用 updateData method,它会使用您提供的数据更新文档。如果文档尚不存在,此写入操作将失败。

  2. { merge: true }作为第二个参数传入setData(),此时会合并数据,如果文档不存在则创建文档.

我通常使用第二种方法,因为我通常不会know/care文档是否已经存在。


我只是 运行 我的一个应用程序中的这段代码:

var ref = Firestore.instance.collection("chat").document();
ref.setData({ 
    'message': "hello", 
    'timestamp': new DateTime.now().millisecondsSinceEpoch,
    'uid': (await getUser()).uid 
  }).whenComplete(() {
    ref.setData({ 'message': "hello good welcome"  }, merge: true);
  });

所以这个:

  1. 新建一个DocumentReference
  2. 在此文档中设置三个字段
  3. 然后更新这些字段之一

在 运行 这段代码之后,我有三个字段:timestampuid 它们的值来自原始 setData(...)message 更新后的值来自 setData(..., merge: true).

的值