2

I'm working with node.js and mongoose. I'm creating a REST API to expose my User model:

var userSchema = new Schema({
 _id: {type:Number},
 username: {type:String},
 age: {type:Number},
 genre:{type: Number,ref:'Genre'},
 country: {type: Number,ref:'Country'}
});

As you can see I decided to include an _id field, so if I want to create a new user I'll need to generate the value for this field, for example:

exports.createUser = function(req,res){
 var user = new User({
    _id: //Generate and assing value here
        //Other properties are retrieved from the request object
 });
};

How could I "generate" or assign a value to my _id field properly? How does mongo deals with this?

user1659653
  • 334
  • 2
  • 5
  • 15
  • 2
    I'd suggest you let MongoDB set the value for your _id field. If you need an additional identifier field you can go ahead define a different field (say key) and use whatever algorithm you feel like for it (a sequential field or a GUID) – Hector Correa Jan 13 '14 at 16:10

2 Answers2

3

I never used mongoose. but if _id is not included in insert query, mongodb driver will generate _ids for you as an ObjectId object. and if you wish to use your own _ids, it's up to you to decide about its type and length, and also you have to guarantee its uniqueness among the collection because any attempt to insert a document with a duplicated _id will fail.

accepted answer of this question may be useful, if you are looking for a method for creating custom _ids that provides a decent degree of guaranteed uniqueness.

Community
  • 1
  • 1
Nasser Torabzade
  • 6,490
  • 8
  • 27
  • 36
  • Ok, so if my POST method doesn't receive the _id param from the incoming request Mongo will generate it for me. Great, this gets rid of my doubt. Thanks. – user1659653 Jan 13 '14 at 17:08
1

mongoDB requires that _id, if supplied, be unique. If _id is not supplied, it is created by the client-side driver (i.e. NOT the mongod server!) as a 12-byte BSON ObjectId with the following structure:

4-byte value representing the seconds since the Unix epoch,
3-byte machine identifier,
2-byte process id, and
3-byte counter, starting with a random value.

more info available here: http://docs.mongodb.org/manual/reference/object-id

Buzz Moschetti
  • 7,057
  • 3
  • 23
  • 33