问题
I'm trying to figure out how to best use MongoDB for a very small and simple use case, but finding the docs somewhat confusing. My document should represent the fact that a user can have many emails. If I follow the documentation the most obvious and simple solution is to use embeds. The problem is when I want to validate the email address for uniqueness, which is AFAIK impossible with embeds (of course I can use map/reduce, but it seems a very poor choice).
I definitely feel like emails don't deserve their own collection, but apparently embedded object doesn't let me do the validation (and if it does, I really don't believe it's going to be efficient). How would you design the schema in this situation ?
回答1:
You can define an index on the email sub-field with { unique: true } set. This will prevent multiple copies of the email address from being stored in the collection.
For example, let's say your documents look something like this:
db.users.findOne() =>
{
"name" : "xxxx",
"emails" : [
{ address: "one@domain.com", validated: false },
{ address: "two@domain.com", validated: true }
]
}
You can define a unique index on the email.address field like this:
db.users.ensureIndex(['emails.address',1], {unique: true})
Now you will get an error if you try to insert the same email address twice. It will also help you optimize looking up users by their email address which is bound to be useful in your app at some point or another.
来源:https://stackoverflow.com/questions/4950099/references-vs-embeds-in-mongodb