Using pg-promise to insert a UUID into the database

I am in the process of setting up a new server and I want each customer to have a unique UUID identifier. My goal is to allow the customers name, parent company, and internal id to be input through a web interface, while the UUID is generated on the server side. How can I properly insert the UUID into the database so that it is stored in the ID column of the table?

Currently, the setup allows me to include the ID with curl for testing purposes. Previously, the code would retrieve all values from the terminal. Now, I am working on modifying the code so that when a new customer is created, their name, parent company, symID, and a UUID generated ID are inputted into the database.

Additionally, I need to pull the symID from a database of IDs which I do not currently have access to. It is uncertain whether this feature will be implemented, so for now, it must be manually entered or left blank.

I'm utilizing pg-promise to write to a postgres database, along with express and bluebird.

//Database setup
...
CREATE TABLE  customer(
  customer_name VARCHAR,
  ID varchar PRIMARY KEY,
  parent VARCHAR,
  symID VARCHAR
);
...

//code to create new user
...
function createUser(req, res, next) {
  const user_id = uuidv4();
  //need to fix id. currently it is user entered and not a uuidv4
  db.none('insert into customer values(${customer_name}, ${ID}, ${parent}, ${symID})',
    req.body)
    .then(function () {
      res.status(200)
        .json({
          status: 'success',
          message: 'Inserted one customer'
        });
    })
    .catch(function (err) {
      return next(err);
  });
}
...

Answer №1

To automatically generate a UUID with a slight modification to your table definition, follow these steps:

If you haven't already installed it, you will need the pgcrypto extension.

    CREATE EXTENSION pgcrypto;  -- if not already installed

    CREATE TABLE customer(
      customer_name VARCHAR,
      ID uuid default gen_random_uuid() PRIMARY KEY,
      parent VARCHAR,
      symID VARCHAR
    );

This will create a type4 UUID. Retrieving its value is similar to retrieving the primary key created by a sequence/serial (at least I believe so).

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

Get the npm distribution package without the need to actually install npm

Is there a way to obtain an npm package without the need for running npm view XXX ... or installing node/npm? Specifically, I am attempting this process on a Linux operating system. ~UPDATE~ I now understand that I should have provided more details about ...

What is the best way to implement an automatic logout feature in asp.net that will log out my site after 10 minutes of inactivity?

Looking for a solution to automatically log out a site in asp.net when it is idle? Here's what you can do: Set the session timeout to 10 minutes in the web.config file under authentication. For instance, if the site has been idle for 9 minutes, you ca ...

How is it possible to retrieve the flex-direction property value of a div using JavaScript?

While attempting to troubleshoot this issue using Windows Chrome 59, I utilized devtools to examine the properties. let element = document.getElementById("divId"); Upon checking the value of the element, I noticed that the object structure displayed: &g ...

Steps to create a scrollable material-ui Modal

After setting up a Modal, I encountered an issue where the text describing my app inside the modal was overflowing, making it impossible to see the top and bottom parts. To solve this problem, I want to implement scroll functionality within the component s ...

Retrieving a property of an object within a function

I'm facing an issue where I am trying to access the properties of objects inside an array in my code to display text values in input boxes that are recovered from local storage after a refresh. However, when I attempt to run a for loop within my appSt ...

The URL may change, but the component remains constant when navigating back

My application consists of two primary components: the Project component and MainContainer. The MainContainer component regularly fetches data using a fetchData method. When moving forward, both the URL and component can change dynamically. However, when m ...

Troubleshooting cross-origin resource sharing problem with Express NodeJS server running on localhost

Utilizing the fetch web API to send a POST request from ReactJS to an Express NodeJS server running on localhost with different ports. Using Client Fetch API fetch("http://localhost:8081/test", { method: "post", mode:"no-cors", headers: { ...

Re-enable the jQuery-ui sortable feature after it has been turned off

Here is a snippet of my jQuery code: var status = true; $('#edit').click(function () { if (status) { $('table tbody').sortable({ axis: 'y', update: function (event, ui) { va ...

Employing jQuery to attach a new div to a dynamically generated div following a successful AJAX request

Currently, I am utilizing the marvelous WP-Polls plugin for WordPress, which boasts an innovative AJAX polling system. My main objective is to append a hidden div (.comment-block) to a fresh div (.voted) that will be dynamically injected into the DOM by th ...

Error encountered in Google's Structured Data Testing Tool

<script type="application/ld+json"> {"@context" : "http://schema.org", "@type" : "LocalBusiness", "name" : "mywebsite.com", "description": "Lorem ipsum dolor sit amet", "image" : "http://mywebsite.com/image.jpg", "telephone" : "987654321", ...

The issue of asynchronous nested callbacks not functioning properly within each iteration of a for loop in Node.js

I have been using the code snippets below to retrieve followers of a specific user stored in mongodb. Here is an example of a saved user JSON: { "_id":{ "$oid":"5440f606255cd4740e88ed21" }, "username":"test2", "email":"test2%40gmail.com", " ...

The Socket.io Namespace does not support the adaptor method

I am currently working on an application where I need to create dynamic namespaces. Whenever a new namespace is created, I attach a redis-adapter to it for scalability reasons. However, when implementing this process, I encounter the following error: var ...

The Moongose array indexOf never seems to reach completion

I am currently facing an issue with using Mongoose Array indexOf to verify if an ID exists in an array of reference objects from another schema. Below is the schema structure, where dishes represent the array: const mongoose = require('mongoose&apos ...

Delay the fading in of an element using jQuery

Is there a way to remove the pause between the images in my JavaScript/jQuery slideshow when fading in and out? I attempted using a small delay, but it still didn't eliminate the blank space. Any suggestions? Check out the code on jsfiddle: https://j ...

Changing the size of icons in an Alert using Material UI with React

Recently, Material UI unveiled the new 'Alert' component. Everything seems to be working well, except for the fact that I can't find a way to adjust the size of the icon. Here is my code snippet: <Snackbar open={true}> <Alert ...

Saving information to a hidden div using jStorage

Currently, I am utilizing jStorage for storing data in local storage. When I store the data using console.log() and later retrieve it using $.jStorage.get(), I found that the values are not being assigned to the hidden div. Can someone provide guidance o ...

nested sequential ajax calls

I am attempting to run a couple of functions with ajax calls inside them in sequence. However, I cannot execute them asynchronously as they both start simultaneously. Here is my code: function engine_start() { a1(); a2(); } a1() { $.ajax( ...

A simple guide on how to surround every incorrect input index in mapped inputs with red borders

I am incorporating a modal that corresponds each element of the object newCompanies to a specific row: {newCompanies.map((company, index) => { return ( <div> <div className="side- ...

The function "collection.find()" can only accept a maximum of two arguments

const roomSchema = new mongoose.Schema({ roomname: { type: String, required: true }, users: { type: Array, required: true }, createdDate: { type: Date, default: new Date() }, admins: ...

Javascript handling scrolling and repositioning

When using the scrollBy() method in the window object of JavaScript, there are two arguments required. But what do these arguments actually represent? The resource I am currently studying from states that it is "the number of pixels to scroll by," but I am ...