Skip to content

Generating unique keys for child objects #43

@Devwulf

Description

@Devwulf

Hello! If I have this schema:

schema.set("users/$userId", {
    name: "string",
    "pets?": {
        "$petId": {
            name: "string",
            "awards?": {
                "$awardId": {
                    name: "string"
                }
            }
        }
    }
});

which are mapped to these models:

class User {
    public name: string;
    public pets?: {
        [key: string]: Pet;
    }
}

class Pet {
    public name: string;
    public awards?: {
        [key: string]: Award;
    }
}

class Award {
    public name: string;
}

Is there a way to auto-generate all the child keys simply by pushing a filled in top-most node into the database, like so?

const award = new Award();
award.name = "Some Award";

const pet = new Pet();
pet.name = "Some Pet";
pet.awards = {
    "*": award
};

const user = new User();
user.name = "Some User";
user.pets = {
    "*": pet
};

await db.ref("users").push(user);

Currently, the only way I could see to do this is to have this monstrosity of a code just to give the child nodes their own auto-generated keys:

const award = new Award();
award.name = "Some Award";

const pet = new Pet();
pet.name = "Some Pet";

const user = new User();
user.name = "Some User";

db.ref("users")
    .push(user)
    .then(ref => {
        db.ref(`users/${ref.key}/pets`)
            .push(pet)
            .then(ref2 => {
                db.ref(`users/${ref.key}/pets/${ref2.key}/awards`)
                    .push(award);
            });
    });

Is there a better way of achieving this? Thanks!


Edit: Seems I was too tired last night to realized this is also possible:

const award = new Award();
award.name = "Some Award";

const pet = new Pet();
pet.name = "Some Pet";

const user = new User();
user.name = "Some User";

const userRef = await db.ref("users").push(user);
const petRef = await db.ref(`users/${userRef.key}/pets`).push(pet);
const awardRef = await db.ref(`users/${userRef.key}/pets/${petRef.key}/awards`).push(award);

But the problem is still there. This solution really doesn't scale well, once nodes get deeper further down. It would be great if there's a way to automatically generate unique keys for child nodes in object collections, preferably a feature in this library by default.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions