buttonsrtoys
buttonsrtoys

Reputation: 2771

How to save objects created with the "new" operator to Firestore?

I have a simple typescript Notification class that I'm trying to instantiate and save to firestore

 let notification = new Notification(
    new User(followerDoc.username, followerDoc.photoUrl)
  );
  _usersRef
    .doc(uid)
    .collection("notifications")
    .add(notification)

Which throws

Error: Value for argument "data" is not a valid Firestore document. Couldn't serialize object of type "User" (found in field "users.0"). Firestore doesn't support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).

I can expand the object manually and save it like this:

  _usersRef
    .doc(uid)
    .collection("notifications")
    .add({
      isRead: notification.isRead,
      users: [{username: notification.users[0].username, photoUrl: notification.users[0].photoUrl}],
      notNamedCount: notification.notNamedCount,
      type: "followers",
    })

But that's more work than I'd like to do. Is there a way to save objects created with the "new" operator to firestore?

Upvotes: 1

Views: 480

Answers (2)

Marek Wasyluk
Marek Wasyluk

Reputation: 312

I was looking for a solution for a similar issue and found some quick and simple one.

The trick is to convert the custom JavaScript objects to JSON string and parse it back to regular JavaScript object. You can simply do this with the following code using static methods of JavaScript's standard, built-in JSON object:

JSON.parse(JSON.stringify(customObjectOfAnyClass))

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317750

No, it's not possible. The error message is telling you that you must provide a plain JavaScript object whose keys and values are the fields you want to create in the document. The Firestore SDK will not accept a custom object. Consider instead making a method on your Notification object that converts it to a plain object, like you would expect from any object with a toJSON method.

Upvotes: 2

Related Questions