Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detected an object of type "Timestamp" that doesn't match the expected instance

I'm wondering why is the Timestamp object is not working as I expect?

It works in test environment (I use Mocha), but throws error when it has been deployed.

index.ts

import { Timestamp, QuerySnapshot } from "@google-cloud/firestore";
....

async someFunction() {
   let col = firestore.collection("mycollection");
   let now = Timestamp.now();
   let twentyMinsAgo = Timestamp.fromMillis(now.toMillis() - (1200 * 1000));

   return col
      .where('LastEdited', '>=', twentyMinsAgo) //This throws error
      .get()
}

Stack Trace

Argument "value" is not a valid QueryValue. 
Detected an object of type "Timestamp" that doesn't match the expected instance. 
Please ensure that the Firestore types you are using are from the same NPM package.
      at Validator.(anonymous function).err [as isQueryValue] (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/validate.js:99:27)
      at CollectionReference.where (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/reference.js:940:25)

package.json

"dependencies": {
   ....
   "@google-cloud/firestore": "^0.16.0",
   "firebase-admin": "~6.0.0",
   "firebase-functions": "^2.0.5"
}
like image 797
Yosi Pramajaya Avatar asked Oct 02 '18 13:10

Yosi Pramajaya


People also ask

How do you post a timestamp on firestore?

So, you first need to convert it to native js Date object and then you can perform methods on it like toISOString() . Store as unix timestamp Date. now , it'll be stored as number i.e. 1627235565028 but you won't be able to see it as readable Date in firestore db.

How do I convert firestore timestamp to date?

firestore. Timestamp. fromDate to convert the a date to a Firestore timestamp. We call toDate on the timestamp object to convert it back to a JavaScript date.

What is Servertimestamp firestore?

Server timestamps are a valuable tool for your app that uses Firestore. They ensure that timestamp values for representing the current moment in time are correct, both in client code and in security rules.


1 Answers

Now I get it why it throws an error. Because I import Firestore object separately, whereas I should just use Firestore object from Firebase Admin SDK.

What I changed:

  1. remove "@google-cloud/firestore" dependency from package.json

  2. Use admin.firestore.Timestamp object.

index.ts

async someFunction() {
   let col = firestore.collection("mycollection");
   let now = admin.firestore.Timestamp.now();
   let twentyMinsAgo = admin.firestore.Timestamp.fromMillis(now.toMillis() - (1200 * 1000));

   col.where('LastEdited', '>=', twentyMinsAgo) //Now ok
      .get()
}
like image 111
Yosi Pramajaya Avatar answered Oct 27 '22 05:10

Yosi Pramajaya