Code review request - creating unique id from documents totals

Hi, For my need I need to generator document ids from the total document in the bucket and I search for solutions and I could not find and I make my own solution. I’m I doing right?

function generateId() {
  return new Promise((resolve, reject) => {
    collection.get("ads", async (error, result) => {
      if (error) reject(error);
      else {
        const count = result.content.count;
        const id = parseInt(count, 10).toString(16).toLowerCase();
        const newCount = count + 1;
        await collection.upsert("ads", { count: newCount });
        resolve(id);
      }
    });
  });
}

function create(document) {
  return new Promise(async (resolve, reject) => {
    const id = await generateId();
    document.id = id;

    collection.insert(id, document, async (error) => {
      if (error) {
        if (error.message === "document exists") {
          const id = await create(document);
          resolve(id);
        } else reject(error);
      } else resolve(id);
    });
  });
}

Hi Marsh,

Couchbase supports atomic counters. Have you considered using a one to generate the IDs? Here’s an overview of counters, and here’s a description of the API for working with counters in version 3 of the node.js SDK.

Thanks,
David

1 Like