使用 angularfire2 将新的子对象添加到 firebase 中的现有对象

Adding a new child object to an existing object in firebase using angularfire2

我将用户数据存储在 firebase 中

users : {
    -KamJGmnL8S4Nn_okIcc : {
        name: "Someone",
        email: "example.com",
        website: "somesite.com"
    },
    -laeghmnw8S4Nn_9inb47 : {
        name: "Someone",
        email: "example.com",
        website: "somesite.com"
    }
}

我需要向用户添加一个新对象 { collections: <key> : { ... }, <key>: { ... } },比如上面对象中的第一个用户。我需要能够推送到 collections,因为它可以有多个对象。

如何使用 angularfire2 执行此操作?

您可以使用 list 来单独 push 它们:

const uid = "-KamJGmnL8S4Nn_okIcc";
const list = angularFire.database.list(`users/${uid}/collections`);
list.push({ name: "collection-a" });
list.push({ name: "collection-b" });

或者您可以使用 object 将它们 update 在一起(在 multi-location 更新中):

const uid = "-KamJGmnL8S4Nn_okIcc";
const obj = angularFire.database.object(`users/${uid}`);

let collections = {
    `collections/${obj.$ref.push()}/name`: "collection-a",
    `collections/${obj.$ref.push()}/name`: "collection-b",
};
obj.update(collections);

请注意,推送密钥是在客户端生成的,您可以通过不带参数调用 push 来生成一个。