Search code examples
javascriptgoogle-cloud-firestore

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?


Solution

  • 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.