0

I have a collection and i want to both create document and then add to its arrays values or if document exist only add the values to the arrays. Here what I've tried.

addMessage() {
    if(this.message.length < 30 && this.message.length > 10) {
      alert('ok')
        var new= db.collection("messages").doc(this.alias)
        new.set( {
          messages: this.message,
          date: Date.now()
        })
      } else {
        alert('no')
      }

when i use set like above it works BUT i want to add values to array so i try and use add but i get error "new.add is not a function"

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I see no array of values in the code you shared. Are you sure the code in your question actually reproduces the problem? Calling `new.add()` makes very little sense, as `new` is a `DocumentReference`, which doesn't have an `add` method. – Frank van Puffelen Feb 21 '20 at 01:16
  • when I use" add" instead of "set" above for the values "message" and "date" which are the values i want to add the existing array of the collection "messages" and document "this.alias" i get error. is there no way to perform such action? – engineer jen Feb 21 '20 at 01:24
  • Aha... that definitely won't be done by calling add on the `new` variable, which is a `DocumentReference`. To add a message to an existing array of messages, you will need to first *load* the document, then add the message to the array, and then finally write the result back to the database. See https://stackoverflow.com/a/48235053 for an example and https://stackoverflow.com/a/46773121/209103. – Frank van Puffelen Feb 21 '20 at 01:36
  • thanks for link. and according to second answer here you can do it with update method. so its not definitely wont work. – engineer jen Feb 21 '20 at 01:47

0 Answers0