1

Data structure

"classrooms" : [
    {
        id : ObjectId("class1")
        "students" : [
            ObjectId("student1")
        ],
    },
    {
        id : ObjectId("class2")
        "students" : [
        ]
    }
],
"students" : [
    {
       "id" : ObjectId("student1"),
       "firstname" : "Ciljan",
       "age" : NumberInt(23)
    },
    {
       "id" : ObjectId("student2"),
       "firstname" : "John",
       "age" : NumberInt(19)
    }
]

The need

I have to provide a document where there are classrooms and students. Students could be assigned to a specific classroom, but not always, so a student could keep free. With the previous data structure, I have the subdocument "students" that provides the list of all the available students both assigned and not assigned. I can assign a student to a classroom storing the student id in the classrooms students array.

Problem

How can I retrieve these data in order to have for each classroom all the records about their assigned students?

Andrea Limoli
  • 155
  • 1
  • 3
  • 12

1 Answers1

0

Do you mean something like Classroom.find({}).populate('students')? That'll return an array of Classrooms with the student fields populated.

Robin Yang
  • 66
  • 4
  • Maybe, but this "populate" function doesn't exist for the MongoDB Node.js Native Driver. Maybe is this command for Mongoose? – Andrea Limoli May 06 '16 at 07:00
  • the mongoose module has 'populate' already built in: http://mongoosejs.com/docs/api.html#document_Document-populate In looking at your snippet, it looks like classrooms and students are part of a larger Schema, in which case the deep-populate plugin is what you need: https://www.npmjs.com/package/mongoose-deep-populate Once you register the plugin with the schema, the call is LargerSchema.find({}).deepPopulate('classrooms classrooms.students') – Robin Yang May 06 '16 at 07:17
  • Thank you very much, although I have to use just **MongoDB Node.js Native Driver** and not Mongoose. The module that you link is always related to a Mongoose Schema that for my logic implementation I can't use. Maybe I have to do it myself. – Andrea Limoli May 06 '16 at 07:23
  • Ah, I see. In that case, no, there isn't a way, but there have been a few solutions offered here: http://stackoverflow.com/questions/19678259/nodejs-mongodb-how-to-query-ref-fields – Robin Yang May 06 '16 at 07:37