Update fields in nested objects in firestore documents?

In case somebody is using TypeScript (like in Cloud functions for example) here is the code to update nested fields with dot notation.

var setAda = dbFirestore.collection('users').doc('alovelace').update({
    `first.${variableIfNedded}.test`: "12345"
});

Peter's solution's great, but it's not works with dynamic key. Following code can works with it:

var nestedkey = 'test';
var setAda = dbFirestore.collection('users').doc('alovelace').update({
    [`first.${nestedkey}`]: "12345"
});

If you don't want an exception that occur if 'first' field doesn't exist, try using set with {merge: true} option instead of update.

var setAda = dbFirestore.collection('users').doc('alovelace').set({
        first : {
            test: "12345"
        }
}, {merge: true});

Edit:

Thanks to @Shane Walker, the latest version(9.8.1) of Firestore has been changed so that update works the same as set with {merge: true} option.

Firebase JavaScript SDK Release Notes


According to the link you provided, it says this:

If your document contains nested objects, you can use "dot notation" to reference nested fields within the document when you call update():

Therefore you need to use dot notation to be able to update only one field without overwriting, so like this:

var setAda = dbFirestore.collection('users').doc('alovelace').update({
    "first.test": "12345"
});

then you will have:

 first
  test: "12345"
  test2: "abcd"