1

I'm trying to find out if there is a best practice on handling CRUD on nested MongoDB documents from a client application like a MEAN stack application. The answers don't have to be specific to MongooseJS or directly connecting to MongoDB in the client, it's more on the concept. How to handle CRUD on nested documents?

Here's my sample document:

{
    "company":"Acme Industries",
    "website":"http://www.acme.com",
    "active":true,
    "contacts":[
        {
            "firstName":"Wile",
            "lastName":"Coyote",
            "dateCreated":"4/3/2015",
            "address":"123 Main St",
            "city":"Yuma",
            "state":"AZ",
            "postalCode":"84938",
            "phoneNumbers":[
                {
                    "Home":"(333) 555-8958",
                    "Cell":"(444) 940-3484"
                }
            ],
            "emailAddresses":[
                {
                    "Home":"wile@coyote.com",
                    "Work":"info@acme.com"
                }
            ]
        }
    ]
}

My client application will have an interface for these different forms:

  1. Add/Edit Company
  2. Add/Edit Contact
  3. Add/Edit Phone
  4. Add/Edit Email Address

I know about creating child schemas for each nested document. Is this a better way to go than simply managing the child data in each node of the root document?

It seems that this needs to be handled similarly to a relational schema, where I create 4 different CRUD scenarios for each independent area that needs to be managed. Or is there a better way? There doesn't seem to be clear documentation on how to do this.

King Wilder
  • 629
  • 1
  • 7
  • 19

1 Answers1

0

For something this nested I would typically go with creating the child schemas separately, and then link those to their proper document based on id (set the contact schema to have a field called userId, which is equal to the current user's mongoId). That might aid in the editing simply by reducing the number of nests you have to deal with.

If not, $push (for add) and $set (for edit) are amazing friends.

Sanky
  • 26
  • 1
  • 3
  • Is this really an unusually nested document? For what you describe, are you saying to have the child documents in separate collections, or just create the nested documents as separate schemas and still live inside the root document? – King Wilder Nov 16 '15 at 04:05
  • It's not that unusually nested. I'd created them as separate collections and link them, but that's just me/the conventions we follow. – Sanky Nov 16 '15 at 19:50
  • No offense, but storing them in separate collections and relating them kind of defeats the purpose of this whole NoSql document storage concept, don't you think? You might as well use an RDBMS instead. – King Wilder Nov 18 '15 at 18:18