Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

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.

share|improve this answer

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: (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!

share|improve this answer

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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