Louis
Louis

Reputation: 2618

how to update firestore subcollection field

I am try to update a field in firestore but I can't find the right call:

changeAlertState(senderId, receiverId, alertType, bool){

  let type = alertType == 'toBe' ? 'toBeAlerted' : 'toAlert';

  this.afs.firestore
  .collection("books")
  .doc(senderId + '/' + receiverId)
  .update({
                        [type]: bool
                    })
  .then(() => {
                console.log("Contact " + receiverId + " alert successfully updated!");
            });
}

Here's the DB: enter image description here

I get this error:

FirebaseError: [code=invalid-argument]: Invalid document reference. Document references must have an even number of segments, but books/33KlbrBypXMe888vpO7dXgDVrfY2/hLh7Ao7IABZBukEpGFK1I8lq1rx1 has 3

Upvotes: 1

Views: 1907

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 600130

You're passing part of the field path into the call to doc(). That won't work, as you need to pass (only) the document ID to into doc. After that you then build a field path for the field that you want to updated, by separating the segments of the path with a .

var value = {};
value[receiverId+"."+type] = bool;
this.afs.firestore
  .collection("books")
  .doc(senderId)
  .update(value)

Also see the documentation on updating fields in a nested object.

Upvotes: 1

Jake Lee
Jake Lee

Reputation: 7989

Basically, the database structure must go collection, document, collection, document etc

This is explicitly stated in the documentation:

Documents live in collections, which are simply containers for documents.

and

A collection contains documents and nothing else. It can't directly contain raw fields with values, and it can't contain other collections.

If you could share more information about your desired structure (a more complete screenshot for example) this would help. This example of how to convert to a properly nested collection / document setup may help too.

Upvotes: 0

Related Questions