Reputation: 334
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?
Upvotes: 2
Views: 11360
Reputation: 6710
I never used mongoose. but if _id
is not included in insert query, mongodb driver will generate _id
s for you as an ObjectId object. and if you wish to use your own _id
s, 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 _id
s that provides a decent degree of guaranteed uniqueness.
Upvotes: 3
Reputation: 7578
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
Upvotes: 1