Search code examples
arraysmongodbmean-stackmeanjsmongoose-schema

MongoDB: Do these objects belong in subdocument arrays or a new collection?


I'm building a MEAN.js app (a beginner experiment project), and my model calls for data that belongs to a specific user to be stored. Here's the model:

{
        "_id" : ObjectId("57b633f677d71aae1b8b56dc"),
        "pauses" : [ 
            {
                "_id" : ObjectId("57b633f877d71aae1b8b56dd"),
                "momentResumed" : null,
                "momentPaused" : ISODate("2016-08-18T22:17:28.222Z")
            }, 
            {
                "_id" : ObjectId("57b633fb77d71aae1b8b56de"),
                "momentResumed" : null,
                "momentPaused" : ISODate("2016-08-18T22:17:31.641Z")
            }, 
            {
                "_id" : ObjectId("57b6392877d71aae1b8b56df"),
                "momentResumed" : null,
                "momentPaused" : ISODate("2016-08-18T22:39:36.032Z")
            }
        ],
        "momentCompleted" : ISODate("2016-08-18T22:39:33.366Z"),
        "momentStarted" : ISODate("2016-08-18T22:17:26.747Z")
}

I need to store a lot (hundreds or thousands) of these per user, and I'd like to add more fields to this as my app evolves and I add new features. Up to this point I've been stuffing them into an array property in each user document (meaning I now have an array of documents that contain arrays), but this is making it difficult to access the data in the sub-array, and I'm becoming concerned that it's not a sustainable model.

Could some more experienced MongoDB devs weigh in? Is this a sustainable model, or should I move all of these objects to a new collection and then figure out a good way to connect them to my user objects?


Solution

  • I went with my gut and moved these objects to their own collection, and it was definitely the right decision. All my queries can be simplified.