Using a UUID as the default ID in a Postgres database system is a straightforward process

As I transition to postgres from mongodb due to the recent announcement, I've noticed that the IDs are simply numerical and auto-incremented. I've attempted a few solutions:

  1. Setting the default ID to a UUID with a lifecycle hook - Unfortunately, this had no effect.
  2. Trying to install bookshelf-uuid

Does anyone have any guidance on how to achieve this? I really do not want the post ID to be an automatically incremented number.

Answer №1

When it comes to auto-incremented ids and uuids, they represent different concepts. Using uuids as primary keys often involves using random values, making duplicates highly unlikely due to the vast range of possible values.

To create an auto-generated uuid primary key, you can use the following SQL statement:

CREATE TABLE my_table (
    id UUID DEFAULT MD5(RANDOM()::TEXT || CLOCK_TIMESTAMP()::TEXT)::UUID PRIMARY KEY,
    … other column definitions …
);

The pgcrypto extension offers a function for generating random uuids as well:

CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE my_table (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    … other column definitions …
);

It's worth noting that starting from Postgres 13, installing the pgcrypto extension for gen_random_uuid() is no longer required.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preserving Scroll Location Through Back Button Usage and Ajax Manipulation of the Document Object Model

Currently, I am incorporating a feature where results are loaded in using ajax with an infinite scroll. However, there is an issue when a user clicks on an item in the list and navigates away from the page - upon returning by clicking the back button, they ...

Increasing the size of a div container based on the position of the cursor on the

I recently stumbled upon a fantastic website where two images slide left and right based on mouse movement. When the cursor is on the right, the right part of the image expands, and when it's on the left, the left part expands. You can check out the ...

Sending a function as a callback to children components in order to update a specific child component

I am currently working on developing a Navbar component that undergoes slight changes when a user logs in through a SignIn component. Here is an overview of how my application is structured: Initially, I have defined a state in the App component where aut ...

What is the best way to handle the completion of the mongoose .exec function?

I am a bit confused about asynchronous code in Node.js and Mongoose. In simple terms, I want to post an array of usernames and check if each username is in the database. If it is, I want to add it to the valid array, otherwise, add it to the invalid array. ...

Reproducing a table row

Here is the table structure I am working with: <table id="customFields" class="table table-bordered table-hover additionalMargin alignment"> <thead> <tr> <th colspan="2"></th> <th>Some Title</ ...

Incorporating a variety of classes by utilizing loops

Looking to add a class to specific li elements - the 1st, 4th, and 7th, the 2nd, 5th, and 8th, and the 3rd, 6th, and 9th. Is this possible? Is there a way to achieve this? ...

Searching for documents in MongoDB that meet specific criteria has become possible through the use

Criteria: COUNT the total number of documents in the collection WHERE objects.objectType is 'group' AND (objects.objectType is NOT 'person' AND relation is 'Exposed_to') Expectation: should return the count of all documents W ...

Encountered an Issue in Integrating TailwindCSS with NextJS Due to postcss.config.js Issue

I recently made the switch from Vite to NextJS by following the official migration guidelines. However, when I attempted to incorporate tailwindcss into my Next project, I encountered an error similar to what is shown in the image linked below. View the e ...

Performing CRUD operations with mongoose and express

My express app is currently being developed with mongoose, and the goal is to integrate it with React for the front end. In my customer controller, I have outlined some CRUD operations, but there are aspects of this approach that I find unsatisfactory. W ...

Issue with displaying jqplot in a jQuery page

Currently, I'm utilizing jqmobile pages for switching between various pages in an html5 application. One of these pages features a jqplot chart. Below is the code snippet: <div data-role="page" id="page-two" data-title="Page 2"> &l ...

Can the Route be modified in Next.js?

I have developed search functionality that navigates to "/search/xxxx", but it is located in the header. Every time I perform a search, the route gets repeated and becomes "/search/search/xxx". Could you suggest any way other than usin ...

Postgres.js Date Range query failing to fetch any results

Recently, I have been utilizing the Postgres.js npm module to interact with a PostgreSQL database Below is the code snippet for executing the query: let startDate = '2020-01-28 08:39:00'; let endDate = '2020-01-28 08:39:59'; let table ...

Converting JSON object to a string

I have an object that contains the value "error" that I need to extract. [{"name":"Whats up","error":"Your name required!"}] The inspector displays the object in this format: [Object] 0: Object error: "Your name required!" name ...

Instantaneous data refresh using Firebase Cloud Functions

Currently, I am working on developing a chat feature in React using Firebase cloud functions. However, I am facing an issue where I do not receive updates when a user sends a message. Below is the code snippet that I have been working with: const app = a ...

Encountering a 401 Error while using Laravel Sanctum/Airlock

Currently, I am utilizing Laravel as the back-end for my innovative Next JS application, with Sanctum being leveraged for authentication purposes. While session authentication operates smoothly on the front end, issues arise when attempting to send reque ...

I am unable to retrieve the complete set of data from Redis using Redis-OM and Next.js

In my application, I have a blog feature where I use Redis as the database and redis-om for managing it. The model for the blog in the app looks like this: const model_blog = new Schema(Blog,{ title : {type : "string"}, description : {t ...

What could be the reason for e.target.value being undefined?

Can someone explain why e.target.value is returning undefined when logged to the console in this simple component? The value should be defined within the element, so I'm confused as to why e.target is not giving the correct value. const NavBar = () = ...

Tips for avoid having the router.asPath useEffect triggered twice on initial load in a NextJs application when using getServerSideProps

I am in the process of creating an exploration page that utilizes URL query parameters (utilizing NextJs pages with getServerSideProps). When an external user visits the URL domain.com/explore?type=actions&category=food, it will retrieve data for "act ...

Determine the estimated download duration using the $http protocol

I am experiencing an issue with a function that calculates the time it takes to download a text file (3MB in size) from my server. While it works well for single requests, when I attempt to run multiple requests simultaneously, the time spent waiting for a ...

html2canvas encountered a CORS error when trying to retrieve images from an external domain

I have been attempting to export a react component as a PDF file. Here are the steps I have followed: Converting the component into an image using html2canvas Creating a PDF document Attaching the image to the PDF The component contains images with URLs ...