References vs embeds in MongoDB

ぃ、小莉子 提交于 2019-12-11 14:19:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!