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"

4
  • 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. Commented Feb 21, 2020 at 1: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? Commented Feb 21, 2020 at 1: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 stackoverflow.com/a/48235053 for an example and stackoverflow.com/a/46773121/209103. Commented Feb 21, 2020 at 1:36
  • thanks for link. and according to second answer here you can do it with update method. so its not definitely wont work. Commented Feb 21, 2020 at 1:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.