mongoDB/mongoose:如果不为空,则为唯一 [英] mongoDB/mongoose: unique if not null

查看:45
本文介绍了mongoDB/mongoose:如果不为空,则为唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法强制唯一的集合条目但前提是条目不为空.e示例架构:

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 字段且 valuenull 的多个文档,仅允许多个文档没有 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆