Prashin Jeevaganth
Prashin Jeevaganth

Reputation: 1343

admin.firestore.FieldValue.serverTimestamp() not working with Firebase Realtime Database

I am trying to write a messaging application with Firebase Realtime Database, which already has some functionality on Cloud Firestore. I wrote the following code snippet in a file messages.js

const admin = require('firebase-admin');
const config = require('./config');

admin.initializeApp(config);//config information

const realtime_db = admin.database();


const { uuid } = require("uuidv4");

const {
    generate_message_structure,
} = require("../util/schema");


exports.async_create_message = async function(data, context) {
    try {
        const message = generate_message_structure(data);//creates a Javascript Object

        const message_log_id = "Some_id";//derived from a function
        //Some interactions with Cloud Firestore



        const generated_token = uuid();
        await realtime_db.ref(`messages/${message_log_id}/${generated_token}`).set(message);

        console.log(message);//output shown later

        console.log("Message created");
        console.log(`message_id of ${generated_token}`)
    } catch (error) {
        console.log(error);
    }
}

I wrote my tests at the bottom of the same file, and ran node messages.js to create a record in the database.

const mockMessage = {};//capitalised constants are strings

mockMessage[MESSAGE_BODY] = "Test body";
mockMessage[MESSAGE_SENDER_ID] = "Alice_id";
mockMessage[MESSAGE_RECEIVER_ID] = "Bob_id";
mockMessage[MESSAGE_IMAGE] = {
    uid: "random_id",
    url: "google.com"
};

exports.async_create_message(mockMessage);

The output from my console.log as annotated earlier has the following structure.

{
  body: 'Test body',
  sender_id: 'Alice_id',
  receiver_id: 'Bob_id',
  image: { uid: 'random_id', url: 'google.com' },
  last_updated: ServerTimestampTransform {},
  created_at: ServerTimestampTransform {},
  seen: false
}

but when I check the record on my database, all fields are present except the last_updated and created_at timestamp fields. May I know what's wrong with this code snippet?

Upvotes: 2

Views: 749

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

You're trying to use a constant for Firestore in interacting with the Realtime Database. While both databases are part of Firebase, they're completely separate, and you can't use the API for one with the other.

To write the server-side timestamp to the Realtime Database use:

ref.set(firebase.database.ServerValue.TIMESTAMP)

Also see the Firebase documentation on ServerValue.

Upvotes: 1

Related Questions