0

I want to generate id of the newly created object as string instead of BSON::ObjectId('59afe79b92caf8948b000005').

I am using mongoid of version mongoid (4.0.2) .

Is there anything like idGeneration of this page https://docs.meteor.com/api/collections.html .

I want to create id as random string(SWpabpucouNBRJZoh) so that it will work with our meteor application.

Any suggestion will helpful for me.

Thanks,

Hare Ram
  • 743
  • 2
  • 7
  • 19

2 Answers2

0

If you generate it at your end and assign an _id field in insert query, mongo shall accept your _id. But if you don't specify any field by the name _id then mongoDB very intelligently creates an _id field which is generated with some algorithm which can be used for sorting purpose in future.

here is the information for how Object ID is generated by mongoDB. Click Here

You can self generate an _id which is around 17 character (depends how long you need it). But before inserting make sure it does not already exists. MongoDB indexes the Keys identified by field _id. You can click here to know more how to generate your desired key. Take hints and develop your own code.

Ankur Soni
  • 5,725
  • 5
  • 50
  • 81
0

As Ankur Soni pointed out, inserting items in the MongoDB without the _id property will result in Mongo creating its own. If you want to create your own id's, you can use something like a GUID generator (as seen here: Create GUID / UUID in JavaScript?) to do the trick:

function guid() {
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
    .toString(16)
    .substring(1);
}
Magicbjørn
  • 619
  • 9
  • 23