Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

node.js - 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).

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}

Or in the shell:

db.users.ensureIndex({email: 1}, {unique: true, sparse: true});

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.

See http://docs.mongodb.org/manual/core/index-sparse/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...