سؤال

I'm using Node, Express and MongoDB (with Mongoskin) for a webbapp.

New client accounts are created through a web form, requiring inputs such as 'Company', 'Contact person', 'Email' et cetera...

When creating new clients there are some fields that have to be unique when saving to the database. This inputs are: 'Company', 'Slug' and 'Email'

Company needs to be unique. Slug is generated from the company name, and also needs to be unique.

Ex. 'Café Rosegarden' and 'Cafe Rosegarden' are two different company names, but will generate the same slug: 'cafe-rosegarden'.

Email. I think this need to be unique... but I'm actually not sure

Right now i have three single unique indexes on these fields.

Question 1: Is indexes the only (best?) way to assert uniqueness on a field?

Question 2: I'f im using a compound index, how does it handle uniqueness? Can i for example say that email only has to be unique in combination with one specific company name?

هل كانت مفيدة؟

المحلول

Yes, adding a unique index to a field is almost always the best way to ensure its uniqueness in the collection.

When using a compound index, MongoDB ensures that each doc in the collection has a unique combination of field values. So if you only had a compound unique index over company and email, you could have more than one doc with the same company or email, just as long as the combination of the two is unique.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top