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