简体   繁体   中英

firebase.database.ServerValue.TIMESTAMP return an Object

I'm working on a web project with Firebase. I call:

firebase.database.ServerValue.TIMESTAMP

This snippet from the Firebase documentation shows how to set a timestamp:

var userLastOnlineRef = firebase.database().ref("users/joe/lastOnline");
userLastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);

To also have the value available in your code, you need to listen for the value:

userLastOnlineRef.on('value', function(snapshot) {
    console.log(snapshot.val());
});

You'll see the value event fire twice (on the device that sets the value): once for the initial client-side estimate of the timestamp and once for the actual value from the server.

It's expected that you will use firebase.database.ServerValue.TIMESTAMP in data that's written to the Firebase database. It's a placeholder for the actual time on the server and will be replaced when the server receives and writes the data.

You will see the actual timestamp value when you read the data from the database or when any listeners you have might have already configured fire (for child_added , child_changed , or value events etc.).

It's explained in the documentation here :

 {TIMESTAMP: non-null Object}

A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) as determined by the Firebase servers.

Just to add some more to answer from @cartant:

admin.database.ServerValue.TIMESTAMP returns a non-null Object and is a placeholder value for auto-populating the current timestamp. It doesn't contain the actual timestamp . The database will replace this placeholder when it will execute the command.

It works as you expect when you are using it inside a database.ref but outside of it is just an useless Object.

See this SO Answer for more.

This is what I had to do:

firebase.firestore.FieldValue.serverTimestamp()

Source:

https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue

Version 9, based on docs<\/a> :

import { updateDoc, serverTimestamp } from "firebase/firestore";

const docRef = doc(db, 'objects', 'some-id');

// Update the timestamp field with the value from the server
const updateTimestamp = await updateDoc(docRef, {
    timestamp: serverTimestamp()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM