you can call the Schema # index method to create the index
let urlSchema = new Schema({ url: String, status: Number } ); urlSchema.index({ url: 1 }, { unique: true, background: true, dropDups: true });
you can listen to the creation of the index event.
let UrlModel = mongoose.model('url', urlSchema); UrlModel.on('index', function(error) { if (error && error.message) { console.log(`Url collection create index error:${error.message}`); } });
Note: the index creation process is asynchronous. When you create a unique index, you cannot insert duplicate data. or index creation fails;
许 庆 钢
source share