kenberkeley
kenberkeley

Reputation: 9856

Mongoose: does a custom _id need to be declared as an index and be unique

Here is the common way to define a collection structure with Mongoose :

var UserSchema = new Schema({
    _id: Schema.Types.ObjectId,
    username: String,
    ...
});

And Now I want _id field declared as Number type :

var UserSchema = new Schema({
    _id: Number,
    username: String,
    ...
});

The problem is, do I need to declare more infomation about _id ? Such as :

var UserSchema = new Schema({
    _id: {type: Number, required: true, index: {unique: true}},
    username: String,
    ...
});

I am not sure whether MongoDB would do it automatically.

if you know the answer, could you leave a comment below ? Thank you!

Upvotes: 5

Views: 3852

Answers (1)

kenberkeley
kenberkeley

Reputation: 9856

Well, after some practice, I realized that, MongoDB would set _id as PRIMARY KEY (NOT NULL + UNIQUE INDEX) automatically. So, just type:

_id: Number,
...

Upvotes: 6

Related Questions