0

I am building a course system. Each course has multiple sections, each section has multiple steps. My datastructure is as follows:

{
    "_id" : "Mtz4DMTwMMKWTWbzE",
    "slug" : "how-to-be-awesome",
    "title" : "How to be awesome",
    "description" : "In 4 easy lessons.",
    "createdAt" : ISODate("2014-08-25T13:33:24.675Z"),
    "sections" : [ 
        {
            "title" : "Be cool",
            "description" : "Title says it all really",
            "steps" : [ 
                {
                    "title" : "Wear sunglasses",
                    "description" : "Always works."
                }, 
                {
                    "title" : "Be funny",
                    "description" : "Make an occasional joke. But no lame ones."
                }
            ]
        }
    ]
}

This worked while adding steps;

Course._collection.update( { _id: course._id, sections: section }, {
    "$push": {
        "sections.$.steps": step
    }
})

But I can't figure out how to update a step. I tried to give the steps an ID and do it like that, but it's not working, apparently because it's two arrays deep, and you can't have two positionals ($) in a query. I tried something like this:

Course._collection.update( { _id: course._id, 'sections.steps._id': step._id }, {
    "$set": {
        "sections.steps.$.title": "test updated title"
    }
})

But this gave the following error:

can't append to array using string field name: steps

Is there a way to do this? Or is my schema design off?

Thanks!

Rijk
  • 11,032
  • 3
  • 30
  • 45
  • possible duplicate of [Update embedded object inside array inside array in MongoDB](http://stackoverflow.com/questions/10465849/update-embedded-object-inside-array-inside-array-in-mongodb) – dgiugg Aug 28 '14 at 13:21
  • Found a lot of duplicates.. Apparently this is [just not possible](https://jira.mongodb.org/browse/SERVER-831) in MongoDB. Makes me wonder why you would ever use nested documents. As long as you're plain adding and fetching it's fine, but updating a doc from the second level is just not possible. :/ – Rijk Aug 28 '14 at 13:23
  • 2
    The limitation is with nested arrays, not with nested documents. Schema design is the way around problems like this. Why not have sections or steps be the top level documents? A course is just the result of a find over all the sections/steps with the same course identifier on them. – wdberkeley Aug 28 '14 at 18:39
  • Right, that's how I solved it for now. I guess my design was off. Just thought it was a good case for using embedding, as a step will never be queried outside of a section, and a section will always be fetched as part of a course. They're just smaller parts of the same, like chapters and pages in a book. – Rijk Aug 29 '14 at 13:02

0 Answers0