question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Error when persisting nested objects

See original GitHub issue

Environment details

Steps to reproduce

  1. call function ref.doc(id).set(params, options), which params is a object like:
{
  "notifications": {
    "web": "a random token string"
  },
  "updatedAt": 1519320011313
}

Expected behavior

  • Persist the object

Actual behavior

  • I got error Cannot encode type ([object Object]) to a Firestore Value. The [object Object] is the nested object ( {web : a random token string} ).

I realized the function isPlainObject at line 1428 returns true for {notifications…}, but returns false for the nested object {web: …}, as it has no Object.prototype property.

//firestore/src/document.js 1428

function isPlainObject(input) {
  return (
    typeof input === 'object' &&
    input !== null &&
    Object.getPrototypeOf(input) === Object.prototype
  );
}

When I tried to force input to be an object

function isPlainObject(input) {
  return (
    typeof input === 'object' &&
    input !== null &&
(Object.getPrototypeOf(input) === Object.prototype) || (Object.getPrototypeOf(Object.create(input)) === Object.prototype)
  );
}

I got another error for the other value at not nested object: Argument \"data\" is not a valid Document. Object prototype may only be an Object or null: 1519320772620.

Using lodash 's isObject method:

function isPlainObject(input) {
    return require('lodash').isObject(input) //returns true for both objects
}

I got the error Argument \"data\" is not a valid Document. obj.hasOwnProperty is not a function

How can I handle this problem? Thank you in advance.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:14 (6 by maintainers)

github_iconTop GitHub Comments

10reactions
BkunScommented, Jan 8, 2019

Had the issue working with GraphQL (resolver), fixed it by

data = JSON.parse(JSON.stringify(data));

GraphQL does pass the data in as an object, but somehow there might be something missing inside the object, causing the object failed to pass firestore validation. Re-creating the object might hurt the performance a little, but that’s the only way I find out to solve it.

1reaction
manwithsteelnervescommented, Jun 26, 2020

I just went through the reason shared earlier why its not supported. That makes total sense. Here I don’t want to use explicit dot notation string and direct firestore methods to update. This is because its difficult to maintain if I change a variable name.

However, I was able to solve it with some additional steps.

In updateUser method

  1. Convert the data with JSON.parse(JSON.stringify(data))
  2. Run a for loop for each key of data and check if its of type FieldValue
  3. If its field value, I update the parsed data from step 1 to the field value
public async updateDocument<T>(resourcePath : string, data : {[fieldPath: string]: any }, type : { new(): T }) : Promise<void>
  {
    const start = Date.now();

    const documentRef   : DocumentReference   = getDatabase().doc(resourcePath);

    // Updating timestamp
    data._updatedAt = Date.now();

    const jsonData = JSON.parse(JSON.stringify(data));
    Object.keys(data).forEach(key => {
      if(data[key] instanceof FieldValue) {
          jsonData[key] = data[key]; //Resetting the values back as field value class instances are allowed custom/special class objects
      }
    });

    await documentRef.update(jsonData);
    
    console.log(`[Time : ${Date.now() - start} ms] Update Document : ${resourcePath}`);
  }

Also, as you notice, its the problem with the firestore FieldValue class values as its a special operation and may be processed differently internally. As mentioned, I don’t want to miss the type information so can’t go with direct firestore updates (similar to examples of dot notation shown over here. They totally aren’t type safe - favorites.color)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Springboot not persist nested object - Stack Overflow
Recently I start learning java and spring boot, so I decided make a basic prototype service system. But I getting some problems on...
Read more >
Cannot persist entity with newly created nested sub entities
This error usually occurs when you create entity A, set it as attribute of entity B, and save only entity B. CascadeType.PERSIST solves...
Read more >
Hibernate's “Detached Entity Passed to Persist” Error | Baeldung
If we try to persist a detached entity, Hibernate will throw a PersistenceException with the “detached entity passed to persist” error message.
Read more >
Persist nested Java Object using codec - M220J - MongoDB
Hi @Tarcisio_de_Paulo_Rosa_51215,. I have observed this happens when there is some mistake in the query which is written in the code. I can...
Read more >
PM46193: OBJECT WITH A NESTED EMBEDDABLE ... - IBM
When an object is merged with a nested Embeddable, the following exception is seen: ... nonfatal user error> org.apache.openjpa.persistence.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found