user6468030
user6468030

Reputation:

Firestore For Loop Batch.Set Only Last Value Document is Created

This is the http firebase function to create event and public event. I am having problem with the for loop only one of the document is created. Basically i am having problem for creating document of prizes in event. As you can see at the picture only last for loop document is created. prizeData[0].amount refers to how many time the prizes for the type 1st prize should be created. prizeData[1], prizeData[2], prizeData[3] refers to prize type 2nd place, 3rd place and consolation prizes. I tried other version of for loop but the result is still the same.

code snippet of problem

let prizeRef = db.collection("events").doc(eventRef.id).collection("prizes").doc();

            for(let i=0; i<Number(prizeData[0].amount); i++){
                console.log(prizeData[0].amount);
                batch.set(prizeRef, {
                    ticketID: "",
                    uid: "",
                    name: "",
                    item: prizeData[0].item,
                    type: prizeData[0].type,
                    redeem: false,
                    redeemTime: null
                });
            }

            for(let j=0; j<Number(prizeData[1].amount); j++){
                console.log(prizeData[1].amount);
                batch.set(prizeRef, {
                    ticketID: "",
                    uid: "",
                    name: "",
                    item: prizeData[1].item,
                    type: prizeData[1].type,
                    redeem: false,
                    redeemTime: null
                });
            }

            for(let k=0; k<Number(prizeData[2].amount); k++){
                console.log(prizeData[2].amount);
                batch.set(prizeRef, {
                    ticketID: "",
                    uid: "",
                    name: "",
                    item: prizeData[2].item,
                    type: prizeData[2].type,
                    redeem: false,
                    redeemTime: null
                });
            }

            for(let l=0; l<Number(prizeData[3].amount); l++){
                console.log(prizeData[3].amount);
                batch.set(prizeRef, {
                    ticketID: "",
                    uid: "",
                    name: "",
                    item: prizeData[3].item,
                    type: prizeData[3].type,
                    redeem: false,
                    redeemTime: null
                });
            }

Overall create function

exports.create = async function (req, res){

    let userID;
    let userData;
    let shopData;
    let eventData = req.body;
    let prizeData = eventData.prizes;
    let batch = db.batch();
    let token = req.headers.authorization.split('Bearer')[1];

    let eventRef = db.collection("events").doc();

    await admin.auth().verifyIdToken(token).then( decodedToken => {
        userID = decodedToken.uid;
        return userID;
    }).catch(err => {
        console.log(err)
        return res.status(500).json({ 
            "status" : "Failure",  
            "action" : "Create event",
            "message" : "Authentication token invalid / Unable to retrieve authentication token"
        })
    });

    await db.collection("users").doc(userID).get().then( doc => {
        userData = doc.data();
        return userData;
    }).catch(err => {
        console.log(err)
        return res.status(500).json({ 
            "status" : "Failure",  
            "action" : "Create event",
            "message" : "User information not found"
        })
    });

    if (eventData.organizer === "decodelab"){
        await db.collection("decodelab").doc("profile").get().then( doc => {
            shopData = doc.data();
            return shopData;
        }).catch(err => {
            console.log(err)
            return res.status(500).json({ 
                "status" : "Failure",  
                "action" : "Create event",
                "message" : "DecodeLab information not found"
            })
        });
    } else {
        await db.collection("shops").doc(userData.shopID).get().then( doc => {
            shopData = doc.data();
            return shopData;
        }).catch(err => {
            console.log(err)
            return res.status(500).json({ 
                "status" : "Failure",  
                "action" : "Create event",
                "message" : "Shop information not found"
            })
        });
    }

    if (userData.role !== "2skk7Y5JQSR2rPtVMtWk" && userData.shopID === eventData.shopID){
        if (eventData.startDate < eventData.endDate && eventData.announcementDate > eventData.endDate){
            batch.set(eventRef, {
                key: eventRef.id ? eventRef.id : '', 
                title: eventData.title ? eventData.title : '',
                coverPic: eventData.coverPic ? eventData.coverPic : '',
                createAt: admin.firestore.Timestamp.now(),
                created: {
                    by: userData.uid ? userData.uid : '',
                    time: admin.firestore.Timestamp.now(),
                },
                deleted_at: null,
                description: eventData.description ? eventData.description : '',
                shortDescription: eventData.shortDescription ? eventData.shortDescription : '',
                points: eventData.points ? Number(eventData.points) : 0,
                endDate: eventData.endDate ? new Date(eventData.endDate) : new Date.now(),
                announcementDate: eventData.announcementDate ? new Date(eventData.announcementDate) : new Date.now(),
                numOfTickets: 0,
                numOfParticipants:0,
                logo: shopData.logo ? shopData.logo : '',//shop
                displayName: shopData.displayName ? shopData.displayName : '',//shop
                name: shopData.name ? shopData.name : '',//shop
                phone: shopData.phone ? shopData.phone : '',//shop
                address: shopData.address ? shopData.address 
                : { country:'',
                    line1:'',
                    line2:'',
                    postcode:'',
                    states:''
                }, 
                shopID: eventData.shopID ? eventData.shopID : '',
                startDate: eventData.startDate ? new Date(eventData.startDate) : new Date.now(),
                subImage: eventData.subImage ? eventData.subImage : ['','','',''],
                termAndCon: eventData.termAndCon ? eventData.termAndCon : '',
                prizes: eventData.prizes ? [{
                    amount: Number(prizeData[0].amount),
                    item: prizeData[0].item,
                    type: prizeData[0].type,
                },{
                    amount: Number(prizeData[1].amount),
                    item: prizeData[1].item,
                    type: prizeData[1].type, 
                },{
                    amount: Number(prizeData[2].amount),
                    item: prizeData[2].item,
                    type: prizeData[2].type, 
                },{
                    amount: Number(prizeData[3].amount),
                    item: prizeData[3].item,
                    type: prizeData[3].type, 
                }
                ]
                : [{
                    amount: 0,
                    item: "",
                    type: "1stPrize",
                },
                {
                    amount: 0,
                    item: "",
                    type: "2ndPrize",
                },
                {
                    amount: 0,
                    item: "",
                    type: "3rdPrize",
                },
                {
                    amount: 0,
                    item: "",
                    type: "Consolation Prize",
                },
                ],
                organizer: eventData.organizer ? eventData.organizer : '',
                numJoined: eventData.numJoined ? eventData.numJoined : 0,
                redeemProcedure: eventData.redeemProcedure ? eventData.redeemProcedure : ''
            });

            let publicEventRef = db.collection("publicEvent").doc(eventRef.id);
            let prizeRef = db.collection("events").doc(eventRef.id).collection("prizes").doc();

            for(let i=0; i<Number(prizeData[0].amount); i++){
                console.log(prizeData[0].amount);
                batch.set(prizeRef, {
                    ticketID: "",
                    uid: "",
                    name: "",
                    item: prizeData[0].item,
                    type: prizeData[0].type,
                    redeem: false,
                    redeemTime: null
                });
            }

            for(let j=0; j<Number(prizeData[1].amount); j++){
                console.log(prizeData[1].amount);
                batch.set(prizeRef, {
                    ticketID: "",
                    uid: "",
                    name: "",
                    item: prizeData[1].item,
                    type: prizeData[1].type,
                    redeem: false,
                    redeemTime: null
                });
            }

            for(let k=0; k<Number(prizeData[2].amount); k++){
                console.log(prizeData[2].amount);
                batch.set(prizeRef, {
                    ticketID: "",
                    uid: "",
                    name: "",
                    item: prizeData[2].item,
                    type: prizeData[2].type,
                    redeem: false,
                    redeemTime: null
                });
            }

            for(let l=0; l<Number(prizeData[3].amount); l++){
                console.log(prizeData[3].amount);
                batch.set(prizeRef, {
                    ticketID: "",
                    uid: "",
                    name: "",
                    item: prizeData[3].item,
                    type: prizeData[3].type,
                    redeem: false,
                    redeemTime: null
                });
            }

            batch.set(publicEventRef, {
                title: eventData.title ? eventData.title : '',
                coverPic: eventData.coverPic ? eventData.coverPic : '',
                createAt: admin.firestore.Timestamp.now(),
                created: {
                    by: userData.uid ? userData.uid : '',
                    time: admin.firestore.Timestamp.now(),
                },
                deleted_at: null,
                description: eventData.description ? eventData.description : '',
                shortDescription: eventData.shortDescription ? eventData.shortDescription : '',
                points: eventData.points ? eventData.points : 0,
                endDate: eventData.endDate ? new Date(eventData.endDate) : new Date.now(),
                announcementDate: eventData.announcementDate ? new Date(eventData.announcementDate) : new Date.now(),
                numOfTickets: 0,
                numOfParticipants:0,
                logo: shopData.logo ? shopData.logo : '',//shop
                displayName: shopData.displayName ? shopData.displayName : '',//shop
                name: shopData.name ? shopData.name : '',//shop
                phone: shopData.phone ? shopData.phone : '',//shop
                address: shopData.address ? shopData.address : { 
                    country:'',
                    line1:'',
                    line2:'',
                    postcode:'',
                    states:''
                }, //shop
                shopID: eventData.shopID ? eventData.shopID : '',
                startDate: eventData.startDate ? new Date(eventData.startDate) : new Date.now(),
                subImage: eventData.subImage ? eventData.subImage : ['','','',''],
                termAndCon: eventData.termAndCon ? eventData.termAndCon : '',
                prizes: eventData.prizes ? eventData.prizes : [{
                    amount: 0,
                    item: "",
                    redeem: false,
                    redeemTime: null,
                    type: "1st Prize",
                    winnerUID: ""
                },
                {
                    amount: 0,
                    item: "",
                    redeem: false,
                    redeemTime: null,
                    type: "2ndPrize",
                    winnerUID: ""
                },
                {
                    amount: 0,
                    item: "",
                    redeem: false,
                    redeemTime: null,
                    type: "3rdPrize",
                    winnerUID: ""
                },
                {
                    amount: 0,
                    item: "",
                    redeem: false,
                    redeemTime: null,
                    type: "Consolation Prize",
                    winnerUID: ""
                },    
                ],
                organizer: eventData.organizer ? eventData.organizer : '',
                numJoined: eventData.numJoined ? eventData.numJoined : 0,
                redeemProcedure: eventData.redeemProcedure ? eventData.redeemProcedure : ''
            });

            batch.commit().then(() => {
                console.log('Create event successfully');
                return res.status(200).json({ 
                    "status" : "Success",  
                    "action" : "Create event",
                    "message" : "Create event successfully"
                });
            }).catch(err => {
                console.log(err);
                return res.status(500).json({
                    "status" : "Failure",
                    "action" : "Create event",
                    "message" : "Failed to create event"
                });
            });
        } else {
            return res.status(500).json({ 
                "status" : "Failure",  
                "action" : "Create event",
                "message" : "START date must be earlier than END date / ANNOUNCEMENT date must be after END date"
            });
        }
    } else {
        return res.status(401).json({ 
            "status" : "Failure",  
            "action" : "Create event",
            "message" : "Unauthorized user access"
        });
    }
};

Total of document generated is only 1 for consolation prizes. Prizes for consolation amount is 10. It should be able to generate 10 documents but only 1 document is generated. Firestore database

Prizes

Upvotes: 0

Views: 225

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

If I correctly understand your code, this is because you re-use the same prizeRef value in your loops, overwriting the prizeRef document again and again.

You should call the doc() method in each iteration, as follows, in order to generate a new DocumentReference:

let prizeRef;

for(let i=0; i<Number(prizeData[0].amount); i++){
    console.log(prizeData[0].amount);
    ///Here, assign a new value to prizeRef, by calling the doc() method
    prizeRef = db.collection("events").doc(eventRef.id).collection("prizes").doc();
    batch.set(prizeRef, {
        ticketID: "",
        uid: "",
        name: "",
        item: prizeData[0].item,
        type: prizeData[0].type,
        redeem: false,
        redeemTime: null
    });
}

//Do the same for the other loops (j, k, l ones)

Upvotes: 1

Related Questions