Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
932 views
in Technique[技术] by (71.8m points)

node.js - Unique index in mongoose not working

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...