I am new to MongoDB and MongooseJS. I am also quite inept at creating databases, sorry.

First question

what is the difference between sub docs and population? Looking at the docs example, a Parent-Children subdoc seems very similar to a Person-Stories population.

Database schema question

Scenario: users can create a number of Canvas. Each Canvas can host a number of Shapes. Each Shape can be of 2 types: Simple, or Complex. A Simple shape can be a Square or a Circle (objects). A Complex shape is made of a Frame and a Material.

            Canvas
               |
             Shape
            /     \       
      Simple       Complex: Frame, Material 
      /     \
Square       Circle

Now, a Shape can be assigned to only 1 Canvas but can be moved between Canvases or live alone outside a Canvas. Frame and Material can be created independently (live alone) and added to a Complex Shape (each Complex Shape can only have 1 frame and 1 material).

Some of the queries I would have to implement are asking for all the shapes in a specific Canvas, or all the shapes that are using a certain material, or again all the Frames that are being used by shapes.

Since the difference between sub-doc and population is not clear to me, I am not even sure how to begin... any help or example would be appreciated (I am not expecting a full and working database schema).

有帮助吗?

解决方案

In answer to part one, the difference is that in a Document-Subdocument scenario the subdocument is stored with the document (as a child document, accessible through the use of dot notation).

In the Mongoose populate scenario, a reference is held to a document in another collection. When you tell mongoose to populate what it does is make another query to MongoDB to get this 'subdocument'.

The main difference I see is that with the mongoose populate method you cannot query for documents using the 'subdocument' properties, whereas you can with the embedded subdocument model.


Edit, subdocument example

So in MongoDB you can store the data as nested subdocuments like so:

{
    _id: acbdbd,
    "property": "value",
    "subdocumentproperty" : {
        "param1": 1,
        "param2": 2
    }
}

This data is only stored with the master document and your querying would be done through the master document, e.g.

db.collection.find({"subdocumentproperty.param1": 1})
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top