Home > Software design >  Secondary IDs in MongoDB
Secondary IDs in MongoDB

Time:03-17

I am aware that _id is already unique. However, due to circumstances, I cannot use it. Each user uses an e-mail address and a username, but I cannot use those either. What I want to use this secondary ID for are friend codes. I do not require them to be short. If they are as long and random as _id, that will not be a problem since users will not have to enter them anywhere. Can such property be assigned during the execution of the insertOne() function?

CodePudding user response:

You cant set unique index for those fields db.users.createIndex( { email: 1, username: 1}, { unique: true } )


Referrer Unique Indexes

CodePudding user response:

You can set a model to generate the _id or not, but for as far as I'm aware there is no option to allow the generation of a second unique identifier automatically.

You could tweak the insertOne method by using uuid as such:

import { v4 as uuidv4 } from 'uuid';

function insertOne(collectionName, document, writeConcern) {
   const [document, ...otherArgs] = args;
   db[collectionName].insertOne({ id: new uuidv4(), ...document }, writeConcern)
}

try {
   insertOne( 'collectionName', { item: "card", qty: 15 } );
} catch (e) {
   print (e);
};

Additionally, if you prefer calling db.collection.insertOne every time and have the id added automatically, you should be able to do so by using it as such (haven't tested it, but it should work):

import { v4 as uuidv4 } from 'uuid';

db.collection.prototype.insertOne = function(document, writeConcern) {
   db.collection.insertOne({ id: new uuidv4(), ...document }, writeConcern)
};

try {
   db.collection.insertOne( { item: "card", qty: 15 } );
} catch (e) {
   print (e);
};
  • Related