1
votes

I am trying to create multiple unique indexes on users collection which are also sparse.

Use case: Allow user to signup with either phone or email

Problem: Mongo db allows creating such indexes, and app runs as expected when connected to a real mongo 3.2 instance. However, with cosmos, email becomes a unique field but not sparse.

Is there a way to achieve this use-case with cosmos via mongodb API? i.e without resorting to check for uniqueness via a fetch query before every insert.

Attempts: Going through cosmos' documentation didn't reveal much. They claim to support mongo 3.2 API, and sparse indexes are not mentioned in caveats. Creating a unique-sparse index with createIndex do not result in error, but only create a unique index. Creating another similar index on a different field doesn't give an error, but don't even create a unique index. It creates a normal index.

Update: Got a response from azure's support team:

Currently we don’t support sparse indexes. You can do this i.e. create a composite index with both the phone and email property.

I don't think a composite index is going to help me with my use case as I want both phone and email to be globally unique in the collection, not only their combination.

1

1 Answers

-1
votes

Can you review this Stack Overflow forum thread: Mongodb unique sparse index

Do the following:

var UserSchema = new Schema({ // ... email: {type: String, default: null, trim: true, unique: true, sparse: true}, // ... });

Notice: unique: true, sparse: true