I am trying to create a unique index in mongoose for a field ("event_key"), and I want mongodb to not save if I try to create a duplicate entry. I looked at the docs, and it seems all I need to do is set index: {unique: true}
in the schema, but I can't seem to get it to work. I've tried several different permutations and still can't get it to work.
In addition, required: true
doesn't seem to be working too since I can save an entry even if I do not pass in an event_key. I'm probably missing something really stupid, and wondering if anyone can help?
Schema
var WistiaAnalyticSchema = new Schema({
event_key: {type: String, required: true, index: {unique: true}},
visitor_key: String,
created: {type: Date, default: Date.now},
ip: String,
})
Trying to add to database
WistiaAnalytic.create({event_key: '1402230270487e0.2668362990953028'}, function(err) {});
WistiaAnalytic.create({event_key: '1402229819163e0.4385743956081569'}, function(err) {});
WistiaAnalytic.create({ip: '1402229819163e0.4385743956081569'}, function(err) {});
WistiaAnalytic.create({event_key: '1402229819163e0.4385743956081569'}, function(err) {
console.log(err)
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…