Append to array Firebase

China☆狼群 提交于 2020-01-22 02:42:08

问题


I'm using Firebase and Vuejs to create an database element, which has object array inside.

That's how the object looks, and I want to add tasks through the form into the 'moreTasks' tab.

I tried using this, but it just creates new entity in the database.

      db.collection('Tasks').add({
    tasker: this.tasker.taskerName
  })

I also tried checking API but I couldnt understand the refs, because I was using different methods to achieve that goal.

creatTask() {
  db.collection('Tasks').add({
    task_id: this.task_id,
    name: this.name,

...

What would be correct way to approach this problem?


回答1:


You can append an item to an array using FieldValue.arrayUnion() as described in the documentation. For example:

// Atomically add a new region to the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});



回答2:


The accepted answer used to be correct but is now wrong. Now there is an atomic append operation using the arrayUnion method: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

This is true as long as you are using firestore and not real time db (which I assume is the case from the tags)



来源:https://stackoverflow.com/questions/48083784/append-to-array-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!