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?
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?
Share Improve this question asked Jan 13, 2014 at 16:01 user1659653user1659653 3342 gold badges6 silver badges15 bronze badges 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) – Hector Correa Commented Jan 13, 2014 at 16:10
2 Answers
Reset to default 3I 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.
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/manual/reference/object-id
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744362879a4570555.html
评论列表(0条)