1
votes

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)
});
1
Mongoose creates indexes in the background, so if you're doing this all in one go it may not work as expected as you end up adding the docs before the index has had a chance to be created. - JohnnyHK
@JohnnyHK Thank you for your comment! Would you know of a workaround then? - Dan Tang
adding to @JohnnyHK, to add delay instead you need to run all these commands one after another. For this you can use async.js. CHeckout this ink for more info stackoverflow.com/questions/17181248/… - Harpreet Singh

1 Answers

5
votes

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)
    });
});