问题
I have created a mongoose model that has an email field. I want it to be unique if a value is provided by a user but I want it to be empty is a user has not provided any value. I have found a good mongodb reference here: https://docs.mongodb.com/manual/core/index-partial/#partial-index-with-unique-constraints that could work but I don't know how to make it work on mongoose
This is how the field looks like right now
email: {
type: String,
index: true,
unique: true
}
If I leave it the way it is, I cant create multiple documents with an empty/null email field
回答1:
You can have something like :
email: {
type: String,
index: {
unique: true,
partialFilterExpression: { email: { $type: 'string' } },
},
default : null
}
but do read below link, before you actually implement it, as defaults seems to work only on new document inserts :-
Mongoose v5.6.9 Documentation
来源:https://stackoverflow.com/questions/57433942/how-can-i-use-partialfilterexpression-on-a-mongoose-model