How do I create a field that references a sub-array of a collection in mongoose?

1

Imagining the following structure (illustrative example only):

Collection: Schools

[
   {
      "_id":"abc123",
      "nomeEscola":"escola1",
      "turmas":{
         "_id":"ccc333",
         "nomeTurma":"Turma1"
      }
   },
   {
      "_id":"abc122",
      "nomeEscola":"escola2",
      "turmas":{
         "_id":"ddd444",
         "nomeTurma":"Turma1"
      }
   }
]

Now, let's say I'm going to create a new collection of students, and I want her schema in mongoose to have ID TURMA and no ESCOLA

StudentModel:

let mongoose = require('mongoose');
Schema = mongoose.Schema;

let alunoSchema = new Schema({
    _id : {type: Schema.Types.ObjectId},
    nomeAluno : {type: String},
    idTurma: {type: Schema.Types.ObjectId, ref : 'Escolas'},
},  {collection : 'Alunos'});


var aluno = mongoose.model('Aluno', alunoSchema);

module.exports = aluno;
  

How do I ensure that idTurma will reference the class id and not the school id?

    
asked by anonymous 13.09.2018 / 14:18

1 answer

1

Good morning! You just need to reference the attribute of the document that will be referenced.

idTurma: {type: Schema.Types.ObjectId, ref : 'Escolas.turmas'}
Viewing your student schema, you can omit the _id attribute, it is generated automatically when you save a document to the base. If you want to assign the _id of it, before entering the database, you can assign the value of the _id direct.

let ObjectId = require('mongoose').Types.ObjectId; 
aluno = new Aluno()
aluno._id = ObjectId()

Kisses

    
13.09.2018 / 15:03