Gustavo Berwanger
Gustavo Berwanger

Reputation: 724

mongoose - avoid duplicate when all fields are equal to new entry

so I have a mongoose schema in my node application with two fields: tag and task, and I want to be able to save entries where the combination of both properties doesnt exist yet.

For example: my DB already has the following entries:

I want to be able to create {tag:tag2, task:task2}, but not {tag:tag1, task:task1} again, so I guess I cant use primary or unique in any of those fields, since they can repeat, except when their combination already exists

so which query should I use to save? Or should I find if it already exists first?

Upvotes: 0

Views: 270

Answers (1)

cheekujha
cheekujha

Reputation: 801

Use Unique Compound Indexing

db.users.createIndex( { "tag": 1, "task": 1 }, { unique: true } )

For more info visit the Link

Upvotes: 3

Related Questions