Filip Vojtíšek
Filip Vojtíšek

Reputation: 91

Mongoose with unique boolean of true

I know how to set a string to be unique on my schema like this:

string: { type: String, unique: true }

but is there a way to have unique boolean with true value on an object and rest with false(set by default)? What I need is: If I try to save an object with true value and one with true already exists error is returned.

Thank you for your help.

Upvotes: 5

Views: 2143

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311835

You can do this using MongoDB's support for partial indexes that was added in 3.2.

var mySchema = new Schema({ oneTrue: Boolean });
mySchema.index({oneTrue: 1}, {unique: true, partialFilterExpression: {oneTrue: true}});

This will create the unique index on the oneTrue field only where its value is true. That way, multiple docs with a false value are allowed, but only one where it's true.

Upvotes: 12

duncanhall
duncanhall

Reputation: 11431

No, this is not possible.

If you look at the Mongoose Documentation for Unique Constraints, you can see it:

Declares an unique index.

You would need to implement a custom read/write process in order to achieve what you want.

Upvotes: 0

Related Questions