0

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:

  • {tag:tag1, task:task1}
  • {tag:tag1, task:task2}
  • {tag:tag2, task:task1}

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?

Gustavo Berwanger
  • 684
  • 1
  • 5
  • 9

1 Answers1

3

Use Unique Compound Indexing

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

For more info visit the Link

cheekujha
  • 781
  • 4
  • 12