Somewhat related to this question, say that I have an object category which, depending on which type of object I have, has different restrictions on what it contains. (if you can reword the previous sentence to make more sense I'd appreciate it)

For example

var SomeSchema = new Schema({
  _id: ObjectID,
  [... large number of common fields ...]
  type: //Restricted somehow to members of a fixed array
  data: //depending on type, this might be restricted - sometimes an integer, sometimes array, etc...

What's the idiosyncratic method for defining this type of schema? Is it appropriate to define a single schema, and handle the types inside of it's members, or am I better off with separate schema for each type?

3 Answers 3


I think it is difficult to do that in mongodb, mongodb is more a 'dumb' storage of objects and does no interpretation of what it is storing. (Of course is does some smart things needed for indexing etc. but not on the domain model level)

You need to save a type field into the object and write code that reads the object from mongo and does some special things based on the type value. So the domain model should handle all special restrictions that are needed and throws an exception when something is wrong.


I believe that the general problem you are trying to solve is called "Single-table inheritance" or STI. Since Mongo is not a relational database, situations like this are usually solved in the model code, as I.renkerna suggested.

You usually set a column that will hold the model "type", and then handle different types appropriately in the rest of the application.

However, there are some guidelines that can be followed for Mongo:

http://talkminer.com/viewtalk.jsp?videoid=PIWVFUtBV1Q&q= (slides 25 and 26)

Outside of Mongo, you can get a better grasp of the concept from an example in Yii framework:


Best of luck!


Do you mean how to store a class hierarchy in MongoDb? This question shows how to do it using the C# library. I'd say map it simply and let your domain model handle restrictions and the like. Just as if you were doing it with a relational DB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.