vkarpov15 / mongoose-unique-array

Plugin to handle `save()` with `unique` in arrays
Apache License 2.0
12 stars 6 forks source link

Unique in array without unique index? #8

Open bathos opened 5 years ago

bathos commented 5 years ago

If I understand right, this plugin:

  1. is schema level, so one cannot use it to enforce in-document uniqueness on a per-field basis
  2. conflates in-document uniqueness with in-collection uniqueness, so you cannot use it to enforce the uniqueness constraint for an array without giving that array a unique index across all documents in the collection

is that accurate? I was hoping I could use this for both cases where there is and is not a collection-wide uniqueness constraint and it seems like only the former is supported.

vkarpov15 commented 5 years ago

That's correct. You're looking for a plugin that ensures elements in an array are unique within a document, but not within a collection? Can you please describe a use case for that?

bathos commented 5 years ago

The constraint corresponds to any array that’s intended to be used as a set (whether treated as ordered or unordered). Say an array of enum strings or references — blogPost.tags is a ubiquitous example.

I went looking for a plugin because I find myself writing roughly the same validator for array member uniqueness frequently. In my experience at least, the general case (array is a set) is more common than the more specific case this plugin covers (array is a set + members are unique across all documents). That case has come up for me too, of course, I was just hoping this could be used for both.

Mongoose (and mongo proper) provide methods for use when arrays are intended to behave as sets (addToSet, pull). They just don’t come with any built-in validation that lets you enforce that the array remains a set (afaik).

(With my question answered — thanks — feel free to close this issue, unless you want to consider it as a feature request.)

vkarpov15 commented 5 years ago

I'll leave this open as a feature request.

Maxine-van-der-Smissen commented 4 years ago

That'd be very helpful actually, it's exactly what I'm looking for