Kannan T
Kannan T

Reputation: 1759

How to get the defined indexes from Mongoose

I have been trying to find out the indexes which are already created via MongoDB manually( I have created 2d sphere indexes for two fields via mongobooster and creating one via schema by defining it). Now if i run this query in mongodbooster

db.collectionname.getIndexes(); 

It results me the 3 documents with name.key and which indexes i have used. I want to perform this same operation in mongoose i can't find a equivalent query for the same. I tried this

const indexes = OrderSchema.indexes();
console.log('index:', indexes);

But it gives me only one index which i have defined in schema that is _id i need two other fields as well which contains 2d-sphere index how can i get that too. What am trying to achieve here is if 2d sphere indexes are already created don't create an index else create an index that's all am trying to achieve here. Any help is appreciated Thanks

Upvotes: 9

Views: 15769

Answers (2)

Gudari
Gudari

Reputation: 357

If you dont have access to mongoose model, but the mongoose connection was created and you need to get the indexes from a collection you can access by this way:

const mongoose = require('mongoose');
mongoose.connect('myConnectionString', { useNewUrlParser: true }).then(() => {
    getIndexes();
}); 

const getIndexes = async () => {
    const indexes = await mongoose.connection.db.collection('myCollection').indexes();
    indexes.forEach(function (index) {
        console.log(JSON.stringify(index));
    });
};

Upvotes: 1

joeytwiddle
joeytwiddle

Reputation: 31305

Yeah, you can't do it with a schema. You will need to create the model first, and then you can do something like this:

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

Upvotes: 12

Related Questions