Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an object of all models of a Mongoose instance

I know that mongoose.model("myModel") returns the myModel model. But how can I get Mongoose to give me an array/object/list of all models, that are currently registered?

I think that somewhat is a design flaw.

like image 573
buschtoens Avatar asked Feb 26 '13 08:02

buschtoens


People also ask

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.

Which property of Mongoose will help us create a model object?

By default, Mongoose adds an _id property to your schemas. const schema = new Schema(); schema.path('_id'); // ObjectId { ... } When you create a new document with the automatically added _id property, Mongoose creates a new _id of type ObjectId to your document.

What is __ V in MongoDB?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).

Does Mongoose model create collection?

Mongoose by default does not create any collection for the model in the database until any documents are created. The createCollection() method is used to create a collection explicitly.


1 Answers

As of now, there is an offcial way: Mongoose#modelNames().


You can access an object of all your models via mongoose.models. This looks like that:

models:
  { myModel:
    { [Function: model]
      modelName: 'myModel',
      auth: [Function],
      model: [Function: model],
      options: undefined,
      db: [Object],
      schema: [Object],
      collection: [Object],
      base: [Circular] } },

In my opinion fiddling around with API private stuff is bad, so this is a little bit of a design flaw of Mongoose (See LearnBoost/mongoose#1362).

like image 144
buschtoens Avatar answered Oct 17 '22 09:10

buschtoens