Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 962
Kannan T Avatar asked Dec 18 '17 11:12

Kannan T


People also ask

How do I view indexes in MongoDB?

You can find all the available indexes in a MongoDB collection by using the getIndexes method. This will return all the indexes in a specific collection. Result: The output contains the default _id index and the user-created index student name index.

What are indexes in Mongoose?

Indexes are defined through ensureIndex every time a model is compiled for a certain connection / database. This means that indexes will only be ensured once during the lifetime of your app.

What is create index in Mongoose?

createIndex is a function for Mongodb. In Mongoose it is renamed to index Item. index({ "createdAt": 1 }, { expireAfterSeconds: 3600 }) Follow this answer to receive notifications.

What is __ V in MongoDB?

Posted On: Jun 24, 2021. In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.


1 Answers

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);
like image 55
joeytwiddle Avatar answered Oct 03 '22 23:10

joeytwiddle