Given a model instance I need to find the indexes defined on it's schema. A model instance has a schema
property, which in turn has an _indexes
property which contains the information I'm looking for. But I guess the leading underscore marks this property as "private" in the sense of "don't use this property, it's not meant to be accessed directly and can change at any time". Am I right? And if so, what is the correct way to get the indexes from a model instance?
Do you need to get the indexes defined on the mongoose schema or the actual indexes defined on the mongodb server? For the latter, Model.collection.indexes(function(error, indexes) {});
should access the underlying driver's method for getting all indexes defined on the collection. If you're looking for the indexes defined on a schema, which in theory is a subset of the indexes defined on the mongodb server as long as mongoose's index build succeeded, var indexes = Model.schema.indexes();
should work
@vkarpov15 yeah I don't follow.. what is Model.collection? I would be looking to get a representation of the indexes in the database
something like this
https://docs.mongodb.com/v3.0/tutorial/list-indexes/
When I use
let models = mongoose.models;
models.forEach(function(m){
m.collection...
});
I get this "no collection" error
{
"message": "no collection",
"shortStackTrace": "MongoError: no collection\n at _combinedTickCallback (internal/process/next_tick.js:73:7)\n at process._tickCallback (internal/process/next_tick.js:104:9)",
"fullStackTrace": "MongoError: no collection\n at Function.MongoError.create (/Users/alexamil/WebstormProjects/cisco/cdt-now/node_modules/mongoose/node_modules/mongodb-core/lib/error.js:31:11)\n at queryCallback (/Users/alexamil/WebstormProjects/cisco/cdt-now/node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js:212:36)\n at /Users/alexamil/WebstormProjects/cisco/cdt-now/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:455:18\n at _combinedTickCallback (internal/process/next_tick.js:73:7)\n at process._tickCallback (internal/process/next_tick.js:104:9)"
}
pretty weird
Ok this works for me...
router.get('/', function (req, res, next) {
let models = mongoose.modelNames();
async.mapLimit(models, 6, function (name, cb) {
const m = mongoose.model(name);
m.collection.indexes(function (err, indexes) {
if (err && err.message === 'no collection') {
return cb(null, {
[name]: 'no collection'
})
}
cb(err, {
[name]: indexes
})
});
}, function (err, results) {
if (err) {
return next(err);
}
res.json({
success: results
})
})
});
db.getCollectionNames().forEach(function(collection) {
indexes = db[collection].getIndexes();
print("Indexes for " + collection + ":");
printjson(indexes);
});
Most helpful comment
Ok this works for me...