Loki00
Loki00

Reputation: 271

Error: Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value (found in field "chatId")

I've been implementing in my website backend a notification system when a new message is created, the database is structured like in this image:

enter image description here

But when the messages is created this error occured:

Error

Error: Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value (found in field "chatId"). If you want to ignore undefined values, enable `ignoreUndefinedProperties`.
    at validateUserInput (/workspace/node_modules/@google-cloud/firestore/build/src/serializer.js:271:19)
    at Object.validateUserInput (/workspace/node_modules/@google-cloud/firestore/build/src/serializer.js:263:13)
    at validateDocumentData (/workspace/node_modules/@google-cloud/firestore/build/src/write-batch.js:590:18)
    at WriteBatch.set (/workspace/node_modules/@google-cloud/firestore/build/src/write-batch.js:256:9)
    at DocumentReference.set (/workspace/node_modules/@google-cloud/firestore/build/src/reference.js:342:14)
    at /workspace/index.js:200:68
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Index.js

exports.createNotificationOnFirstMessage=functions.region('europe-west1').firestore.document('/chats/{chatId}/messages/{messageId}')
.onCreate((snapshot)=>{
    var recipientArrn = snapshot.data().chatId.split('_');
    // recipientArrn is an array of substring, the first is the sender (index 0), the second is the recipient (index 1)
    return db.doc(`/users/${recipientArrn[1]}`).get()
            .then(doc =>{
                if(doc.exists){
                    return db.doc(`/notifications/${snapshot.id}`).set({
                        createdAt: new Date().toISOString(),
                        recipient: recipientArrn[1],
                        sender: snapshot.data().sender,
                        type:'message',
                        read: false,
                        chatId: doc.chatId,
                    });
                }
            })
            .catch(err =>{
                console.error(err);
            });
})

What can I do to resolve this error?

Upvotes: 0

Views: 1788

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599876

Ad the error message says, you are passing undefined in the value of:

chatId: doc.chatId,

So doc.chatId is undefined, which is not an allowed value for a field in Firestore.

You're probably looking for:

chatId: doc.data().chatId,

Upvotes: 1

Related Questions