Srinivas
Srinivas

Reputation: 1556

How to drop and create indexes in mongoose mongodb

I have been trying to reset the unique key indexes while importing the data as shown below:

const importData = function() {
   UserLocation.collection.dropAllIndexes((err) => {
    if (err) {
      console.trace(err);
      return;
    }
    UserLocation.collection.createIndex({
     Adfrom: 1,
     Adpto: 1
    }, {
     unique: true
    });

    fs.createReadStream(`${__dirname}/../data/import-data.csv`).pipe(parser);
   });
 };

Its working fine in my local environment but when i deploy this code iam getting mongodb connection error because of dropIndex.

Error:
Mongoose default connection to mongodb://localhost:27017/userlocation disconnected
Mongoose default connection error: MongoError: connect ECONNREFUSED 127.0.0.1:27017

How to fix this issue.

Please help !

Thanks

Upvotes: 1

Views: 4296

Answers (2)

ertemishakk
ertemishakk

Reputation: 547

const schema = new Schema({ name: { type: String, unique: true } });
const Customer = mongoose.model('Customer', schema);
await Customer.collection.createIndex({ age: 1 }); // Index is not in schema
// Will drop the 'age' index and create an index on `name`
await Customer.syncIndexes();

You need to sync indexes. Check out this source : https://mongoosejs.com/docs/api.html#model_Model.syncIndexes

Upvotes: 1

Ajitej Kaushik
Ajitej Kaushik

Reputation: 944

You can drop index by

db.collection.dropIndex("//field of which you want to drop index")

Or you can use the index specification document

db.collection.dropIndex( { "//field of which you want to drop index" : -1 } )

It will drop index of the field with value -1.

and collection will be the name of your table,

for eg.

db.pets.dropIndex( { "cat" : -1 } )

Simirlarly for creating index, you can have a quick glance at Create Index.

You can run these commands in your mongo shell.

Upvotes: 1

Related Questions