Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in mongoose

Hello I need to inherit my schemas in mongoose library. Are there complete plugins for that? Or how should I do that myself?

I need to inherit all pre, post, init middleware from a Base schema also.

like image 759
Erik Avatar asked Jan 09 '13 05:01

Erik


People also ask

What is discriminator in mongoose?

Discriminators are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB collection. Suppose you wanted to track different types of events in a single collection.

What is the difference between model and schema in mongoose?

Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What is findById in mongoose?

In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document. For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.

Is schema necessary for mongoose?

Mongoose Schematype is a configuration for the Mongoose model. Before creating a model, we always need to create a Schema. The SchemaType specifies what type of object is required at the given path. If the object doesn't match, it throws an error.


2 Answers

For others looking for this functionality, Mongoose 3.8 now has Schema Inheritance via Discriminator functionality:

https://github.com/LearnBoost/mongoose/pull/1647

like image 73
regretoverflow Avatar answered Sep 16 '22 16:09

regretoverflow


You may want to look at using a Mongoose Plugin:

  • http://mongoosejs.com/docs/plugins.html

A plugin that does what you want 'out of the box' is here:

  • https://github.com/briankircho/mongoose-schema-extend
like image 24
hunterloftis Avatar answered Sep 20 '22 16:09

hunterloftis