mongoDB/mongoose:如果不为null,则为唯一 [英] mongoDB/mongoose: unique if not null
问题描述
我想知道是否有办法强制唯一集合条目,但仅当条目不为空时. Ë 示例架构:
I was wondering if there is way to force a unique collection entry but only if entry is not null. e Sample schema:
var UsersSchema = new Schema({
name : {type: String, trim: true, index: true, required: true},
email : {type: String, trim: true, index: true, unique: true}
});
在这种情况下不需要'email',但是如果保存了'email',我想确保该条目是唯一的(在数据库级别).
'email' in this case is not required but if 'email' is saved I want to make sure that this entry is unique (on a database level).
空条目的值似乎为'null',因此每个邮件都不会通过'unique'选项崩溃(如果有其他用户没有电子邮件).
Empty entries seem to get the value 'null' so every entry wih no email crashes with the 'unique' option (if there is a different user with no email).
现在我正在应用程序级别上解决它,但是很想保存该数据库查询.
Right now I'm solving it on an application level, but would love to save that db query.
thx
推荐答案
从MongoDB v1.8 +开始,您可以通过将sparse
选项设置为true来获得确保唯一值但允许多个文档不包含字段的期望行为.在定义索引时.如:
As of MongoDB v1.8+ you can get the desired behavior of ensuring unique values but allowing multiple docs without the field by setting the sparse
option to true when defining the index. As in:
email : {type: String, trim: true, index: true, unique: true, sparse: true}
或在外壳中:
db.users.ensureIndex({email: 1}, {unique: true, sparse: true});
请注意,唯一的稀疏索引仍然不允许具有email
字段且 value 为null
的多个文档,只有多个文档没有和email
字段.
Note that a unique, sparse index still does not allow multiple docs with an email
field with a value of null
, only multiple docs without an email
field.
请参见 http://docs.mongodb.org/manual/core/index-sparse/
这篇关于mongoDB/mongoose:如果不为null,则为唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!