mongoDB/mongoose:如果不为空则唯一 [英] 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' 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",因此每个没有电子邮件的条目都会因唯一"选项而崩溃(如果有其他用户没有电子邮件).
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.
谢谢
推荐答案
从 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}
或者在shell中:
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:如果不为空则唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!