2

I'm using firebase real-time database with express.js as backend. Here's my data saving snippet code:

const db = require('./firebase_connection').firebaseDatabase

async function saveData(req, model) {
    await db.ref(model).set(req)
    return {"statusCode": "201", "message": "Inserted successfully"}
}

module.exports = { saveData }

This is the json output:

{
  "user" : {
    "email" : "TEST77@TEST.com",
    "full_name" : "Hossein Heydari",
    "password" : "test",
    "phone_number" : 54,
    "role" : "client"
  }
}

But I also need an Id added to database automatically, just like what MongoDB has which is _id

I need firebase to store data with a auto increment Id for any model, what should I do?

Hossein Heydari
  • 1,439
  • 9
  • 28

1 Answers1

5

So, firebase does provide a way to get the unique key when you push the changes, I am not sure if you have tried this:


postsRef.push({
  author: "gracehop",
  title: "Announcing COBOL, a New Programming Language"
});

// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();

// Get the unique key generated by push()
var postId = newPostRef.key;

You can check here for more details.

Or, if you want to create similar what Mongo does then you should create a custom one, create a similar key like Mongo does and keep it in the DB and on every new insert add that ID to the model. You can check here.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35