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?
2
Answers
You cant set
unique index
for those fieldsdb.users.createIndex( { email: 1, username: 1}, { unique: true } )
Referrer Unique Indexes
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 usinguuid
as such: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):