Search code examples
node.jsmongodbmongoosemongoose-schema

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


Solution

  • 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);