Home > Software design >  How to put a variable inside firestore property names in javascript?
How to put a variable inside firestore property names in javascript?

Time:01-14

I'am trying to do put a variable inside a firestore property, Here is my example:

exports.handler = function(admin, data) {
    const userId = data.userId;

    return admin.firestore().collection('users')
    .doc(userId)
    .update(
    {
        `userInfos.${userId}`: admin.firestore.FieldValue.delete()
    })
}

Also I try to declare a string before the query and use this string as a property name yet that cause another failure.

    const newField = `userInfos.${userId}`;

    return admin.firestore().collection('users')
        .doc(userId)
        .update(
        {
            newField: admin.firestore.FieldValue.delete()
        })

Is there any way to do that, or I have to change my data structure?

CodePudding user response:

The quickest way to make that second snippet work is to put the field name in square brackets:

const newField = `userInfos.${userId}`;

return admin.firestore().collection('users')
    .doc(userId)
    .update({
        [newField]: admin.firestore.FieldValue.delete()
    })
  •  Tags:  
  • Related