Home > OS >  Firestore nested maps (object), dot notation doesn't work
Firestore nested maps (object), dot notation doesn't work

Time:11-15

I have a nested maps on Firestore, I am trying to update an object into another object using dot notation but it's concatenate the called key with object name in Firestore, if I update this nested map (object) without dot notation, will overwrite the entire map field.

if (doc && doc.exists) {
        await doc.ref.update({subscription: {chartslab: {
          "options.expiration": new Date(new Date()
              .getTime() (10*24*60*60*1000)),
          "options.updatedAt": new Date().toISOString(),
        }}}).then(() => {
          return res.status(200).send("Document successfully updated!");
        });
      } else {
        await doc.ref.set({subscription: {chartslab: {options: {
          expiration: new Date(new Date().getTime() (5*24*60*60*1000)),
        }}}});
        return res.status(200).send("Done");
      }

Create

Create Firestore data

Update

Update Firestore data

CodePudding user response:

If you are using dot notation to update nested field, you must add the complete path in dot notation as shown below:

await doc.ref.update({
  'subscription.chartLabs.options.expiration': 'value',
  'subscription.chartLabs.options.updatedAt': 'value'
})

There's a package flat which can be useful in this case if you have a lot of nested fields to be updated.

const flatten = require('flat');

const updateObj = flatten({
  subscription: {
    chartLabs: {
      options: {
        expiration: '...',
        updatedAt: '...'
      }
    }
  }
})

Since you are updating the whole 'options' object, you can try this:

await doc.ref.update({
  'subscription.chartLabs.options': {
    expiration: '...',
    updatedAt: '...'
  }
})
  • Related