So I have a user schema with a nested profile property, and I would like to make sure that all profile id's are unique when the profile property exists:
UserSchema = new Schema {
...
...
profile : {
id : {
type : String
unique : true
sparse : true
}
...
...
}
}
When running my tests, however, I am able to save two different users with the same profile.id value. Is the unique attribute not enforced on nested documents? Am I missing something?
After turning on the logging, I am able to see an output like this (I have removed most fields):
Mongoose: users.ensureIndex({ email: 1 }) { safe: undefined, background: true, unique: true }
Mongoose: users.insert({ profile: { id: '31056' }) {}
Mongoose: users.ensureIndex({ 'profile.id': 1 }) { safe: undefined, background: true, sparse: true, unique: true }
Mongoose: users.insert({ profile: { id: '31056' }) {}
The duplicate value is still being inserted.