Reputation: 137
I am trying to create an online presence feature that updates each user's online status using flutter. I am achieving this by using a realtime database, cloud functions, and cloud Firestore.
My problem is when I run my cloud function to detect changes in the realtime database and update the status field in my user's collection in cloud Firestore. It keeps saying it cannot find the document to update.
Here is my cloud function code
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const firestore = admin.firestore();
exports.onUserStatusChange = functions.database
.ref("/{uid}/status")
.onUpdate(async (change, context) => {
// Get the data written to Realtime Database
const isOnline = change.after.val();
// Then use other event data to create a reference to the
// corresponding Firestore document.
const userStatusFirestoreRef = firestore.doc(`users/${context.params.uid}`);
console.log(`status: ${isOnline}`);
return userStatusFirestoreRef.update({
status: isOnline,
last_seen: Date.now(),
});
});
here is the error on onUserStatusChange function
Error: 5 NOT_FOUND: No document to update: projects/posweepay/databases/(default)/documents/users/162057431950849
at Object.callErrorFromStatus (/workspace/node_modules/@grpc/grpc-js/build/src/call.js:31:26)
at Object.onReceiveStatus (/workspace/node_modules/@grpc/grpc-js/build/src/client.js:176:52)
at Object.onReceiveStatus (/workspace/node_modules/@grpc/grpc-js/build/src/client-interceptors.js:342:141)
at Object.onReceiveStatus (/workspace/node_modules/@grpc/grpc-js/build/src/client-interceptors.js:305:181)
at /workspace/node_modules/@grpc/grpc-js/build/src/call-stream.js:124:78
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Realtime database structure
Cloud Firestore database structure
Upvotes: 0
Views: 710
Reputation: 389
From the logs, it looks like you're trying to refer to the document from the user.accountid
rather than using the document identifier.
While the accountid
might be 162057431950849
(I'm guessing this happens to be the UID of the document in your Realtime Database) - the actual identifier for the document in Firestore is 615862116620550
.
This seems like a discrepancy in your data model. A possible solution could be to store the Firestore Document UID in your Realtime Database and use that value to refer to the Firestore Document whenever needed.
Upvotes: 1
Reputation: 598817
While at first glance the UIDs in the screenshots are the same, the error message seems to indicate that there is some mismatch.
To troubleshoot, I recommend using a set-and-merge operation, which will also create the document if it doesn't exist:
return userStatusFirestoreRef.set({
status: isOnline,
last_seen: Date.now(),
}, { merge: true });
With this you can check what new document gets created, and how it compares to the existing document that you expected to be updated.
Upvotes: 0