Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I´m using mongoose and I need to find a model name from a model instance.

In one part of the code I have:

 const schema = new mongoose.Schema({
        name: {
            type: String,
            required: true
        },
        phone: {
            type: String,
            required: true
        }
    }

const schema = new mongoose.Schema('MyData', schema);

let instance = new this({
      name: 'Pete',
      phone: '123'
});

Ths instance variable is passed around in my code. Later I need to find out instance name, but I´m no sure if there is a way to do it, something like:

let instanceName = getInstanceName(instance); <== Expects 'MyData' to be returned

Is that possible using mongoose ?

like image 670
Mendes Avatar asked Oct 31 '17 16:10

Mendes


People also ask

What does Mongoose model return?

mongoose. model() returns a Model ( It is a constructor, compiled from Schema definitions).

Does Mongoose auto generate ID?

_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.

What does findByIdAndDelete return?

The findByIdAndDelete() is a function in Mongoose used to find a document by the _id field and then remove the document from the collection. It returns the document removed or deleted.

What is instance in Mongoose?

An instance of a model is called a document. Creating them and saving to the database is easy. const Tank = mongoose. model('Tank', yourSchema); const small = new Tank({ size: 'small' }); small. save(function (err) { if (err) return handleError(err); // saved! }); // or Tank.


2 Answers

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.

like image 185
Loren Avatar answered Sep 21 '22 20:09

Loren


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

like image 44
Hannah May Avatar answered Sep 20 '22 20:09

Hannah May