Convert json commn type to mongo types "string-id" to UUID("string-id")

Hi dear friends :slight_smile:
I am working on a extension (js) which copies a JSON from the browser in to clipboard ready to be pasted.
For days now I have searched to find how to convert the id type which are string and convert them to UUID type.
e.g:
“id” : " 0b2484c8-c069-4fa3-a23d-b40010ab59da" >to> “id”: UUDI(“0b2484c8-c069-4fa3-a23d-b40010ab59da”)

As well as for “LastUpdated”: “2023-10-23T08:46:13.213Z” >to> “LastUpdated”: ISODate(2023-10-23T08:46:13.213Z),

I appreciate any idea or solution.

Hi @Behzad_Pashaie2,

Welcome to the MongoDB Community forum :sparkles:

Are you looking for any specific conversion method? Also, may I ask the purpose of this conversion? Are you planning to store the data in a MongoDB Collection? If so, you might consider using a JS script to do the conversion process.

Looking forward to your response.

Best regards,
Kushagra

Hi @Kushagra_Kesav_1
Thanks for you kind response. Yes I am looking for a way (in javaScript function\code ) to parse some values to different type (If I am not wrong BSON types!?)

Let me explain it this way :slight_smile:

I have javascript code which copies the response of an API call as a :

json1 :{
“Id”: “b52918ea-3d32-4b5c-ac2c-114ac940c47d”,
“RegDate”: “2023-09-26T00:00:00Z”
}

I need convert\parse json1 to

json2 :{
“Id”: UUDI(“b52918ea-3d32-4b5c-ac2c-114ac940c47d”),
“RegDate”: ISODate(“2023-09-26T00:00:00Z”)
}

The reason to require this is when inserting json1 the “Id” and “RegDate” are inserted as string types while i need them to be UUID and ISODate type.
I have searched a lot. I be so gratefull if help me with a solution\practical approach o this.

BTW here my code in the case you wonder:
As you see the changeMongoType function will do the job as now it only parsers
“Id”: “b52918ea-3d32-4b5c-ac2c-114ac940c47d” to “Id”: “UUID(‘b52918ea-3d32-4b5c-ac2c-114ac940c47d’)" which again is a string and dose not fulfill what I am looking for.

document.addEventListener('DOMContentLoaded', function () {
  const copyButton = document.getElementById('copyButton');
  const msg = document.getElementById('msg');

  copyButton.addEventListener('click', function () {
    // Clear the existing URL list
    msg.innerHTML = '';

    // Get the current active tab's URL
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      const currentTab = tabs[0];
      let url = new URL(currentTab.url);
      //const url = currentTab.url;
      const baseUrl = url.protocol + '//' + url.hostname;

      console.log(url.hash);
      url= new URL(url.hash.replace(/^#/,""),currentTab.url.split("#")[0]);
      console.log("URL >>>"+url);
      // Extract parameters from the URL (adjust as needed)
      const id = url.searchParams.get('id');
  
      const code = url.searchParams.get('code');
  
      const type = url.searchParams.get('type');
      // Construct the new URL
      const newUrl = `${baseUrl}/api/entity/${id}?companyCode=${code}&module=${type}`;
      console.log(newUrl);

      // Make the API call using the current URL
      fetch(newUrl)
        .then(response => response.json())
        .then(data => {
          data._id = data.Id;
          delete data.Id;
           const readyMongoData =  changeMongoType(data);
          // Copy the API response to the clipboard
          copyToClipboard(JSON.stringify(readyMongoData)); // JSON.stringify(data)
          
        }).then(()=>{
          const newMsg = document.createElement('h3');
          newMsg.textContent =  new DOMParser().parseFromString(`Copied to cliboard V4 <span>&#10003;</span>`, 'text/html').body.textContent;
          msg.appendChild(newMsg);
        })
        .catch(error => {
          console.error('API Call Error:', error);
        });

        
    });
  });
});


function copyToClipboard(text) {
  navigator.clipboard.writeText(text)
    .then(() => {
      console.log('URL copied to clipboard:', text);
      // You can add a success message here
    })
    .catch(error => {
      console.error('Error copying to clipboard:', error);
      // You can add an error message here
    });
}

function parseDateToISODate(dateString) {
  const date = new Date(dateString);
  if (isNaN(date)) {
    // Handle invalid date input if necessary
    return null;
  }
  return date.toISOString();
}



///////////////////////////////////////////////////////////////////
function changeMongoType(jsonObj) {
  
    for (const key in jsonObj) {
      if (jsonObj.hasOwnProperty(key)) {
        const value = jsonObj[key];
        
        if (typeof value === 'string' && /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(jsonObj[key])) {
          jsonObj[key] = convertStringToUUIDFormat(value);
        
        }else if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z?$/.test(jsonObj[key]) && isStringADate(jsonObj[key])) {
          jsonObj[key] = `ISODate("${jsonObj[key]}")`.replace(/\"/g, "");
        //  jsonObj[key] = `ISODate("${jsonObj[key]}")`.replace(/\"/g, "");
        } else if (typeof value === 'object') {
          changeMongoType(value); // Recursively process nested objects
        }
      }
    }
    
  return jsonObj;
}

function convertStringToUUIDFormat(input) {
  const regex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
  if (regex.test(input)) {
    console.log(`UUID('${input}')`.replace(/['"]+/g, ''));
    //return `UUID('${input}')`.replace(/['"]+/g, '');
    console.log("input> "+input);
    return    UUID(input);
  
  } 
  return input;
}  

function isStringADate(dateString) {
  // Try to parse the string into a Date object
  const date = new Date(dateString);
  // Check if the parsed date is a valid date and the original string is not "Invalid Date"
  return !isNaN(date) && date.toString() !== 'Invalid Date';
}

function preservId(dateString) {
  // Try to parse the string into a Date object
  const date = new Date(dateString);
  // Check if the parsed date is a valid date and the original string is not "Invalid Date"
  return !isNaN(date) && date.toString() !== 'Invalid Date';
}```

Hope you are doing well. :slight_smile:
Any updates on this issue?
Thanks

Hi @Kushagra_Kesav_1. Any updates. Looking to hear from you.

Hey @Behzad_Pashaie2,

Apologies for the late response.

You can use bson - npm to convert and save the specific UUID in the database. Please ensure that you’re passing a valid UUID string (32 or 36-character hex string) to the constructor, otherwise, it will throw an error.

I’ve tested this in my environment with Node.js v16.20.2, MongoDB node.js driver v5.7.0 and bson v5.0. Sharing the code snippet for your reference:

const { MongoClient } = require('mongodb');
const { UUID } = require('bson');

const url = 'mongodb://localhost:27017';
const dbName = 'test_db';
const client = new MongoClient(url);

const myuuid = new UUID('b52918ea-3d32-4b5c-ac2c-114ac940c47d');


async function saveDocument() {
    try {
        await client.connect();
        console.log('Connected to the server');

        const db = client.db(dbName);
        const collection = db.collection('coll');

        const document = {
            id: myuuid,
            name: 'Sample Document',
            date: new Date("2023-09-26T00:00:00Z"),
        };

        const result = await collection.insertOne(document);
        const insertedDoc = await collection.findOne({ _id: result.insertedId });
        console.log(`Document inserted: ${JSON.stringify(insertedDoc)}`);

    } catch (err) {
        console.log('Error:', err);
    } finally {
        await client.close();
        console.log('Connection closed');
    }
}

saveDocument();

It returns the following output:

Connected to the server
Document inserted: {"_id":"6572a38083fdea63d22d4a6c",
                     "id":"b52918ea-3d32-4b5c-ac2c-114ac940c47d",
                     "name":"Sample Document",
                     "date":"2023-09-26T00:00:00.000Z"}
Connection closed

You can query the same data from the MongoDB Compass and it will return the following:

{
  _id: ObjectId("6572a38083fdea63d22d4a6c"),
  id: UUID("b52918ea-3d32-4b5c-ac2c-114ac940c47d"),
  name: 'Sample Document',
  date: 2023-09-26T00:00:00.000Z
}

Furthermore, for the ISODate part - MongoDB conceptualizes the ISODate within its structure. Here, mongosh wraps the Date object with the ISODate helper. The ISODate is in UTC (Reference). In other programming languages or contexts, it may appear differently. But, if I query the same data from my mongosh it will return the following output where date will be wrapped in ISODate:

test> use test_db
switched to db test_db
test_db> db.coll.find()

{
 _id: ObjectId("6572a38083fdea63d22d4a6c"),
 id: new UUID("b52918ea-3d32-4b5c-ac2c-114ac940c47d"),
 name: 'Sample Document',
 date: ISODate("2023-09-26T00:00:00.000Z")
}

I hope it helps! In case you have any further questions, please feel free to reach out.

Best regards,
Kushagra

4 Likes

Hi @Kushagra_Kesav Thanks a lot i will try this.
Sure this looks a promising answer. I will try and keep you updated.
Wish you a lovely day my friend.
Kind regards,
Behzad

1 Like