Reputation: 13
I'm creating a document using mongoose, and I can't find a way to create unique IDs for a few elements on the document.
For an example:
Document {
_id: ObjectId(...),
title: "Post Title",
comments: [
{ NEEDED_ID: 1, value: "abc"},{ NEEDED_ID: 2, value: "abc"}
],
input: {
isInput: true,
NEEDED_ID: 3,
}
}
Hope you can help me out with it.
Upvotes: 0
Views: 393
Reputation: 216
if you need an id that automatically increments check auto-increment in mongoDB: https://www.mongodb.com/basics/mongodb-auto-increment
example from mongoDB docs above with Atlas:
// create collections
db.createCollection("students");
db.createCollection("counters");
// create trigger
exports = async function(changeEvent) {
var docId = changeEvent.fullDocument._id;
const countercollection = context.services.get("<ATLAS-CLUSTER>").db(changeEvent.ns.db).collection("counters");
const studentcollection = context.services.get("<ATLAS-CLUSTER>").db(changeEvent.ns.db).collection(changeEvent.ns.coll);
var counter = await countercollection.findOneAndUpdate({_id: changeEvent.ns },{ $inc: { seq_value: 1 }}, { returnNewDocument: true, upsert : true});
var updateRes = await studentcollection.updateOne({_id : docId},{ $set : {studentId : counter.seq_value}});
console.log(`Updated ${JSON.stringify(changeEvent.ns)} with counter ${counter.seq_value} result : ${JSON.stringify(updateRes)}`);
};
// Replace <ATLAS-CLUSTER> with your cluster service name.
db.students.insert({
"name":"Jhon Doe"
});
db.students.insert({
"name":"David Smith"
});
db.students.insert({
"name":"Amanda Herny"
});
// get students from atlas
db.students.find().pretty();
if you need to create a random id in node, you can use the crypto
package.
Option 1:
const crypto = require("crypto");
// create id
const _id = crypto.randomBytes(16).toString("hex");
// '4a82db25ba403269c009db0129a032f3'
Option 2:
const { randomUUID } = require("crypto");
const uuid = randomUUID()
// 'e92b8088-7fd2-40fd-ad87-2c16cbedfc94'
EDIT: regarding your comment, randomUUID()
definitely generates a unique id everytime. Double check your implementation of it if it doesn't work for you. You can test uuid generation in a demo script like this:
const { randomUUID } = require("crypto");
numberOfIds = 5;
// generate five unique id's
for (let i = 0; i < numberOfIds; i++) {
const uuid = randomUUID();
console.log(uuid);
// prints 5 id's
// f0151ff5-2656-400f-b4e6-c5549324f8f9
// a8223ae3-6259-4114-951b-8c12c3d932bf
// 3a0404fd-6f5a-40d3-9726-c549f6d62ab4
// 35178ac4-62d5-4654-938e-0ffac378751a
// 458bf08f-07d2-4849-bf67-6f328ff93109
}
Upvotes: 1