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?

1
  • 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) Jan 13, 2014 at 16:10

2 Answers 2

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.

1
  • 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. Jan 13, 2014 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.