sac Dahal
sac Dahal

Reputation: 1241

mongodb reindex the collection not working

I have designed my Schema to have a unique field as .

var bookingSchema = new Schema({
booking_id_customer: {
    type: Number,
    index: { unique: true }

}

}

Due to some changes I am removing the index, my new design looks like.

 var bookingSchema = new Schema({
    booking_id_customer: {
        type: Number

    }
}

But still I get the duplicate key error index message from mongodb.When I provide duplicate bookingId. I tried the reIndex() method.

     var bookingSchema = new Schema({
        booking_id_customer: {
            type: Number

        }
    }
bookingSchema.reIndex();

But I get booking.reIndex is not a function error. My mongoDb is hosted in mlabs. How to overcome this problem. Thank you.

Upvotes: 0

Views: 1947

Answers (1)

Ben Smith
Ben Smith

Reputation: 531

First you need to drop your indexes then reindex the fields when this is finished, so do (ShopModel here is a reference to my collection or model ShopModel sometimes referred to as db.whateverYourCollectionNameIs):

const ShopModel = require('./shop_model');

ShopModel.collection.dropIndexes(function(){
    ShopModel.collection.reIndex(function(finished){
            console.log("finished re indexing")
     })
})

To check your indexes have worked you can run:

ShopModel.collection.getIndexes({full: true}).then(indexes => {
    console.log("indexes:", indexes);
}).catch(console.error);

Upvotes: 2

Related Questions