using ensureIndex in mongodb schema using mongoose

后端 未结 4 1645
走了就别回头了
走了就别回头了 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:23

    First define index on authorName field and if you manually want invoke ensureIndex because of certain requirement then you have to set autoIndex to false. This is what your schema would look like:

    var schema = mongoose.Schema({
        projectName : String,
        authorName : {type : String, index : true}
        comment : [{
            id : String,                                    
            authorName : String,
            authorEmailAddress : { type : String, index : true }    
        }]
    }, {
         // Turn-off auto indexing, we manually need to trigger indexing 
         autoIndex : false 
    });
    

    And based on the requirement you can invoke ensureIndexes method on the model that you have created using this schema i.e. ProjectModel.ensureIndexes();

提交回复
热议问题