Is there a way to get the model name from a mongoose model instance?

The name of the model can be accessed using this instance.constructor.modelName.


I realized I had a model not an instance of a model so I needed to use something else.

If you have a model, you can get the name as below:

const model = mongoose.model("TestModel", schema);
const collectionName = model.collection.collectionName;

If you have a specific item/instance of the model:

const instance = new model({...});
const collectionName = instance.constructor.modelName

as Hannah posted.


In my case I was looking for how to get a discriminator model name from a mongoose model, and the suggested solutions didn't work:

const PerformanceResult = DropDown.discriminator('PerformanceResult', new db.Schema({
    name: { type: String, required: true }
}))
export default PerformanceResult

console.log(PerformanceResult.constructor.modelName) // undefined
console.log(PerformanceResult.collection.collectionName) // DropDown (parent name)

you can use this:

console.log(PerformanceResult.modelName) // PerformanceResult

mongoose version: "^5.11.8"