How to overwrite object Id's in Mongo db while creating an App in Sails

shubhamagiwal92 picture shubhamagiwal92 · Jun 22, 2015 · Viewed 8.1k times · Source

I am new to Sails and Mongo Db. Currently I am trying to implement a CRUD Function using Sails where I want to save user details in Mongo db.In the model I have the following attributes

"id":{
  type:'Integer',
  min:100,
  autoincrement:true
},
attributes: {
    name:{
     type:'String',
     required:true,
     unique:true
 },
    email_id:{
       type:'EMAIL',
       required:false,
       unique:false
},
   age:{
     type:'Integer',
     required:false,
     unique:false
   }
} 

I want to ensure that the _id is overridden with my values starting from 100 and is auto incremented with each new entry. I am using the waterline model and when I call the Api in DHC, I get the following output

"name": "abc"
"age": 30
"email_id": "[email protected]"
"id": "5587bb76ce83508409db1e57"

Here the Id given is the object Id.Can somebody tell me how to override the object id with an Integer starting from 100 and is auto incremented with every new value.

Answer

TechWisdom picture TechWisdom · Jun 22, 2015

Attention: Mongo id should be unique as possible in order to scale well. The default ObjectId is consist of a timestamp, machine ID, process ID and a random incrementing value. Leaving it with only the latter would make it collision prone.

However, sometimes you badly want to prettify the never-ending ObjectID value (i.e. to be shown in the URL after encoding). Then, you should consider using an appropriate atomic increment strategy.

Overriding the _id example:

db.testSOF.insert({_id:"myUniqueValue", a:1, b:1})

Making an Auto-Incrementing Sequence:

  • Use Counters Collection: Basically a separated collection which keeps track the last number of the sequence. Personally, I have found it more cohesive to store the findAndModify function in the system.js collection, although it lacks version control's capabilities.
  • Optimistic Loop

Edit:

I've found an issue in which the owner of sails-mongo said:

MongoDb doesn't have an auto incrementing attribute because it doesn't support it without doing some kind of manual sequence increment on a separate collection or document. We don't currently do this in the adapter but it could be added in the future or if someone wants to submit a PR. We do something similar for sails-disk and sails-redis to get support for autoIncremeting fields.

He mentions the first technique I added in this answer: Use Counters Collection. In the same issue, lewins shows a workaround.