Reputation: 1333
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)
});
Upvotes: 1
Views: 2280
Reputation: 311865
Mongoose creates indexes in the background, so you need to delay your create
calls until index creation has completed. One way to do that is with the 'index'
event of the model:
WistiaAnalytic.on('index', function(err) {
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)
});
});
Upvotes: 5