Setting document field value using Firestore Functions

28 Views Asked by At

I have this function that updates a user's feed after following another user by getting the post IDs of that user's posts and then adding them to a 'user-feed' in the users document. It worked fine until I added the timestamp field in. What I'm trying to do is to add the timestamp from each post to the document that is being created in the user-feed, so that I can get the feed posts by ordering it by timestamp.

Error I'm getting:

Error: Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value (found in field "timestamp"). If you want to ignore undefined values, enable ignoreUndefinedProperties.

 exports.updateUserFeedAfterFollow = functions.firestore.document('/following/{currentUid}/user-following/{uid}').onCreate((snap, context) => {
    const currentUid = context.params.currentUid;
    const uid = context.params.uid;
    const db = admin.firestore();
    functions.logger.log('Function called..')

    return db.collection('posts').where('ownerUid', '==', uid).get().then((snapshot) => {
        functions.logger.log('Fetched posts..')
        snapshot.forEach((doc) => { 
            const postId = doc.id;
              const timestamp = doc.timestamp;
            functions.logger.log('PostID:', postId)
            const writeResult = db.collection('users').doc(currentUid).collection('user-feed').doc(postId);
            writeResult.set({timestamp: timestamp});
        });
        return null;
      })
      .catch((err) => {
        functions.logger.log(err);
      });
  });

I tried to add the timestamp of each post to the document that was created. It doesn't run and gives an error

1

There are 1 best solutions below

7
Doug Stevenson On BEST ANSWER

The error message is coming from this line:

        writeResult.set({timestamp: timestamp});

It's saying that the value of timestamp is undefined, which is not valid in Firestore. In fact, timestamp is always going to be undefined since you're not accessing document fields correctly. To get an object with all the key/value pairs of fields, you should call data() on the DocumentSnapshot instead:

const data = doc.data();
const timestamp = data.timestamp;

Since we can't see the results of the query, nor the contents of the document from the query, we can't tell you anything more that will help.

Also you should make sure you wait for the promise returned by set to resolve before returning from the function. Otherwise, Cloud Functions might terminate your code before it completes.