using ensureIndex in mongodb schema using mongoose

后端 未结 4 1644
走了就别回头了
走了就别回头了 2021-02-06 01:40

I would like to call ensureIndex on the authorName, what is the command and where in this code should I put it?

var mongoose = require(         


        
4条回答
  •  鱼传尺愫
    2021-02-06 02:09

    you can call Schema#index method to create index

    let urlSchema = new Schema({
        url: String,
        status: Number
      }
    );
    urlSchema.index({ url: 1 }, { unique: true, background: true, dropDups: true });
    

    you can listen createing 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 process of creating index is asynchronous.so when you create unique index,you cannot insert duplicate data. or creating index will fail;

提交回复
热议问题