Update fields in nested objects in firestore docum

2019-04-07 18:11发布

I have a data structure like:

enter image description here

I want to edit the value of "test" key in "first" object. I followed the document on https://firebase.google.com/docs/firestore/manage-data/add-data

But it did not work for me.

The nodejs code:

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

The result in firestore: enter image description here

The "test2" key was gone. However, I only want to update the value of "test" and keep the "test2".

Any solution for this problem?

5条回答
欢心
2楼-- · 2019-04-07 18:39

Try this one: Does it work like that?

var setAda = dbFirestore.collection('users').doc('alovelace').update({
        "first.test" : "12345"
});
查看更多
何必那么认真
3楼-- · 2019-04-07 18:40

For those who need something more generic and recursive, here is a function that updates a Foo Firestore document non destructively with a typescript Partial :

private objectToDotNotation(obj: Partial<Foo>, parent = [], keyValue = {}) {
    for (let key in obj) {
        let keyPath = [...parent, key];
        if (obj[key]!== null && typeof obj[key] === 'object')
            Object.assign(keyValue, this.objectToDotNotation(obj[key], keyPath, keyValue));
        else
            keyValue[keyPath.join('.')] = obj[key];
    }
    return keyValue;
}

public update(foo: Partial<Foo>) {
    dbFirestore.collection('foos').doc('fooId').update(
        this.objectToDotNotation(foo)
    )
}
查看更多
别忘想泡老子
4楼-- · 2019-04-07 18:46

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"
});
查看更多
老娘就宠你
5楼-- · 2019-04-07 18:46

Peter's solution's great, but it's not works with dynamic key. This code is far better:

var nestedkey = 'test';
var setAda = dbFirestore.collection('users').doc('alovelace').update({
    [`first.${nestedkey}`]: "12345"
});
查看更多
祖国的老花朵
6楼-- · 2019-04-07 18:56

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"
查看更多
登录 后发表回答