简体   繁体   中英

How to push all the documents in a collection with values to another collection in form of map firestore web

I have products in my cart which on checkout get converted to orders. I want all the documents in cart collection to be mapped as an object map / array in orders collection inside a single document.

function placeOrder(){
    var uid = auth.currentUser.uid
    db.collection('users').doc(uid).collection('carts')
    .get().then((items)=>{
        items.forEach((item)=>{
            var item_key = item.id
           db.collection('users').doc(uid).collection('orders').doc().set({
               items : [item_key]
           })
           db.collection('users').doc(uid).collection('carts').doc(item_key).delete()
        })       
    })
}

Order item IDs => Array field:

...
.get()
.then(snapshot => {
    const ids = snapshot.docs.map(doc => doc.id)

    db.collection('users')
        .doc(uid)
        .collection('orders')
        .doc()
        .set({items : ids})
}

Order item data => Sub-Collection:

...
.get()
.then(snapshot => {
    const batch = db.batch()
    const orderRef = db.collection('users').doc(uid).collection('orders').doc()
    const cartRef = db.collection('users').doc(uid).collection('carts').doc(item_key)

    batch.set(orderRef, { 
        // order fields
    })

    snapshot.forEach(docSnap => {
        batch.set(orderRef.collection('order_items').doc(docSnap.id), {
            // order item fields
        })
    })

    batch.delete(cartRef)
    batch.commit()
}

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