Managing my own custom Id's

2,097 views
Skip to first unread message

Jean-Bernard Moens

unread,
Mar 28, 2013, 1:05:30 PM3/28/13
to mongoo...@googlegroups.com
Hi,

I'd like to manage my own Id's (as the default ones are pretty long and consume bandwidth). The difficulty is that I need to create them (say, by incrementing a counter). But I need to do this in a concurrent environment (Node.JS). Is there a simple example I could follow that creates a schema, with a custom _id and a method(?) that automatically generates the next unique _id, whenever a new document is created?

Thanks,

JB

Mongo Rookie

unread,
Mar 28, 2013, 1:16:06 PM3/28/13
to mongoo...@googlegroups.com
Look here:
http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

Translated to mongoose:
module.exports = function(mongoose) {
 
// Creates a new Mongoose Schema object
 
var Schema = mongoose.Schema;  

 
// Collection to hold counters/sequences for ids
 
var CountersSchema = new Schema({  
      _id
: { type: String, required: true },  
      sequence
: { type: Number, required: true }
   
},{
      versionKey
: false
   
}
 
);

 
// Creates the Model for the Attachments Schema
 
var Counters = mongoose.model('Counters', CountersSchema);

 
var getNext = function(collection, callback) {
   
var query = {_id: collection};
   
var update = {$inc: {sequence: 1}};
   
var options = {upsert: true};
   
Counters.findOneAndUpdate(query, update, options, function(err, counter) {
     
if (err) // handle error

      callback
(counter.sequence);
   
});
 
}


 
return {
    getNext
: getNext
 
}
}



Now you can do something like:
getNext('person', function(id) {
 
// create a new person with the next id
});



This allows you to have a counter/sequence for multiple 'collections', ie I would use this for my person collection.

Please be aware of this.  Probably more more of an issue than consuming bandwidth for a few extra characters in an id.

Warning

Generally in MongoDB, you would not use an auto-increment pattern for the _id field, or any field, because it does not scale for databases with larger numbers of documents. Typically the default value ObjectId is more ideal for the _id.

Reply all
Reply to author
Forward
0 new messages