0

Is there a way to increase the post ID for every document added into the database so my data will look like this.

First insert:

{
    "createdAt": "2020-09-27T21:35:12.276Z",
    "postId": "1",
    "body": "This is my first post",  
}

Second insert:

{
    "createdAt": "2020-09-27T21:37:39.165Z",
    "postId": "2",
    "body": "This is my second post",  
}
exports.postOnePost = (req, res) => {
  if (req.body.body.trim() === "") {
    return res.status(400).json({ body: "Body must not be empty" });
  }

  const newPost = {
    createdAt: new Date().toISOString(),
    postId: ,
    body: req.body.body,
  };

  db.collection("posts")
    .add(newPost)
    .then((doc) => {
      console.log(doc.id)
    })
    .catch((err) => {
      res.status(500).json({ error: "something went wrong" });
      console.error(err);
    });
};
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Bill Cheng
  • 11
  • 2
  • Why do you need to do this? This strategy doesn't scale well (since your auot-increment will be hard to keep up to date under load). It's usually more appropriate to simply accept a random identifier for each document. `add()` is already giving you that ID. – Doug Stevenson Sep 27 '20 at 22:06
  • Because each post has their own number and I wanted to show this number at the client side. I am using a random identifier for the document, I just want to store a number that increments itself when a new post is added. – Bill Cheng Sep 27 '20 at 22:34

2 Answers2

0

Copying the ID into the document is an anti-pattern.

You should let Firestore generate the ID using .add, as you're doing, and let it be just your document key, not a document property, too.

Francesco Colamonici
  • 1,147
  • 1
  • 10
  • 16
  • It doesn't sound like copying the ID isn't exactly what this OP is asking to do. The ask is for an increasing numeric ID to be incremented with each add. Anyway, copying the ID into the document is actually necessary in some cases, as with collection group queries where you want to query the entire collection group by the document ID - this is impossible without copying the ID into the document. – Doug Stevenson Sep 27 '20 at 22:08
0

In comments you said:

I just want to store a number that increments itself when a new post is added.

This is not possible with Firestore. There are no auto-increment fields like you have in some SQL databases. This is because auto increment values don't scale in the way that Firestore requires.

If you want to have an increasing value like this, you will need to keep track of that value somewhere else, such as another document, or some other source altogether, and copy that updated number for each document you add.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441