I am trying to save a unique array of String elements using MongoDB but for some reason it allows me to save duplicates.
I am using mongoose. My code:
schema = mongoose.Schema({
"searchingId": { "type": String,
"unique": true,
"index": true },
"sharedTo" : {
type: [String],
unique: true,
"trim":true
}
}, {collection: 'myCollection'});
Basically the point is to keep a list of email addresses where the user had sent emails and to prevent the user from spamming them. But this schema will allow me to push any string to a sharedTo array and to .save() it no matter whether the duplicates exist. How to prevent this from happening?
EDIT: Lahar's answer does help with my question but not entierly. I would like to prevent user from adding emails if there is at least one duplicate. So basically $addToSet will help with uniqueness but not with my question.