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 });

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

    collection.insert(id, document, async (error) => {
      if (error) {
        if (error.message === "document exists") {
          const id = await create(document);
        } 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.


1 Like