简体   繁体   中英

How can I push elements to array in firestore document collection?

I have a problem. I need to create Basket functionality on food delivery website. What I want is to map through basket items and then if there are two items from the same restaurant push them to specified restaurant in firestore and add them to "Orders" collection as one object.

Lets say:

basket: [
  {id: 0, restaurantId: 0, price: 10, name: bla bla},
  {id: 1, restaurantId: 0, price: 99, name: hoho},
  {id: 2, restaurantId: 15, price: 2, name: DIFFERENT RESTAURANT}
]

For now I created something like that and It does not really work, well it "pushes" item to specified restaurant in "Orders" collection BUT it happens only once, so if object with the same user exists it does not push another one but updates this one that already exist.

basket.map(el => {
  restaurantRef.doc(el.restaurantId).update({
    [`orders.${user.id}.products`]: firebase.firestore.FieldValue.arrayUnion(el),
    [`orders.${user.id}.details`]: {
      name: user.name,
      status: "waiting",
      address: {
        city: "New York",
        ...
      }
    }
  })
})

user.id is from object that stores current user.

So what I am trying to do is push object to "Orders" collection (/restaurants/ restaurantId /orders) with nested array inside.
This should look like this:

orders:{
  userId: {
    products: [{}, {}, {}],
    details: {}
  }, 
  anotherUserId: {
    products: [{}, {}, {}],
    details: {}
  }, 
  userId: {
    products: [{}, {}, {}],
    details: {}
  }, 
}

One user is twice in orders because he might order something a few days ago and today and this is how it should be.
I do not know if I explain this correctly and missed something that you need to help me.

Thanks in advance and I appreciate your time.

The issue could be that arrayUnion only adds unique values. This could be a problem because you are pushing objects, I'm not sure if Firestore checks the contents of the objects to see if they are unique. Maybe try set.(PATCH_OBJECT_HERE, { merge: true}) instead.

Also, maybe a better solution (in regards to db performance) for what you are trying to do is to sort basket items into arrays by restaurantId and then push each array with an update. This brings your updates down from 2 instead of 3. Example of why it may be better: If you have 5 items and they are all from the same restaurant ID, you would be doing 5 updates rather than just 1.

I think your problem that your orders is invalid. Firebase has JSON structure. All keys has to be unique.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM