首页 > 解决方案 > Firestore For Loop Batch.Set 仅创建最后一个值文档

问题描述

这是用于创建事件和公共事件的 http firebase 函数。我对 for 循环有问题,只创建了一个文档。基本上我在创建活动奖品文件时遇到问题。正如您在图片中看到的,仅创建了最后一个 for 循环文档。prizeData[0].amount指应创建多少次类型一等奖的奖品。prizeData[1], prizeData[2], prizeData[3]指奖品类型二等奖、三等奖和安慰奖。我尝试了其他版本的 for 循环,但结果仍然相同。

问题的代码片段

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
                });
            }

整体创造功能

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"
        });
    }
};

生成的文件总数仅为 1 份安慰奖。安慰奖金额为10。应该可以生成10个文档,但是只生成了1个文档。 Firestore 数据库

奖品

标签: node.jsfirebaseexpressgoogle-cloud-firestoregoogle-cloud-functions

解决方案


如果我正确理解您的代码,这是因为您在循环中重复使用相同的值,一次又一次地prizeRef覆盖文档。prizeRef

您应该在每次迭代中调用该doc()方法,如下所示,以生成一个新的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)

推荐阅读