joe.js
joe.js

Reputation: 301

Mongoose unique index for ObjectId field

Trying to create unique index for an ObjectId field. I tried:

var schema = new Schema({
    field: {
        type: Schema.ObjectId,
        ref: 'SomeModel',
        unique: true,
    } });

and...

var schema = new Schema({
    field: {
        type: Schema.ObjectId,
        ref: 'SomeModel',
        index: {unique: true}
} });

I can't get it working and it seems a very common problem.

Upvotes: 0

Views: 1255

Answers (2)

joe.js
joe.js

Reputation: 301

Solved. It was a typo at the type definition, dumb of me...

The type should be:

type: Schema.Types.ObjectId

as jack black noted. I didn't noticed the typo because my code definition still worked for query population. strange behaviour.

Upvotes: 1

jack blank
jack blank

Reputation: 5195

Schema.Types.ObjectId instead of Schema.ObjectId

Upvotes: 1

Related Questions