dannyconnell / localbase

A Firebase-Style Database ... Offline!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to update a value inside a nested object?

OziOcb opened this issue · comments

Let's say I have something like this:

    {
      name: 'Tom',
      age: 32,
      cars: {
        honda: {
          year: 2010,
          color: 'red'
        },
        bmw: {
          year: 2020,
          color: 'black'
        }
      }
    }

Is there a way to update the cars.honda.year without having to update the entire cars object??

My solution:

  methods: {
    addOwner() {
      db.collection("owners").add(
        {
          name: "Tom",
          age: 32,
          cars: {
            honda: {
              year: 2010,
              color: "red",
            },
            bmw: {
              year: 2020,
              color: "black",
            },
          },
        },
        new Date().toISOString()
      );
    },


    // THE SOLUTION!
    async updateOwner(id) {
      // Fetch the document from IndexDb using it's ID
      const collection = await db.collection("owners").doc(id).get();

      // Modify value inside nested object
      collection.cars.honda.year = 2021;

      // Save the document again
      db.collection("owners").doc(id).set(collection);
    },
  },

(inspired by other IndexDb wrappers)