如何在mongodb中分配一个id值?
我正在使用node.js和mongoose。 我正在创build一个REST API来公开我的用户模型:
var userSchema = new Schema({ _id: {type:Number}, username: {type:String}, age: {type:Number}, genre:{type: Number,ref:'Genre'}, country: {type: Number,ref:'Country'} });
正如你所看到的,我决定包含一个_id字段,所以如果我想创build一个新的用户,我需要为这个字段生成值,例如:
exports.createUser = function(req,res){ var user = new User({ _id: //Generate and assing value here //Other properties are retrieved from the request object }); };
我怎么能“生成”或正确地赋值给我的_id字段? mongo怎么处理这个?
我从来没有用mongoose。 但是如果_id
不包含在插入查询中,mongodb驱动程序将为您生成_id
s作为一个ObjectId对象。 如果你想使用你自己的_id
,你可以决定它的types和长度,并且你必须保证它在集合中的唯一性,因为任何尝试插入带有重复_id
的文档都将失败。
这个问题的接受答案可能是有用的,如果你正在寻找一种方法来创build自定义的_id
s,提供了一个相当程度的保证唯一性。
mongoDB要求_id(如果提供的话)是唯一的。 如果没有提供_id,它由客户端驱动程序(即不是mongod服务器!)创build为具有以下结构的12字节BSON ObjectId:
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.
更多信息可在这里: http : //docs.mongodb.org/manual/reference/object-id