How to create a field that references a sub-array of a Collection in Mongoose?

Asked

Viewed 554 times

1

Imagining the following structure(Merely illustrative example):

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 go create a new student charter, and I want her schema in Mongoose have the ID of TURMA and nay of ESCOLA

Alunomodel:

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 go reference the Class id and not the School id?

1 answer

2


Good morning! You only need to reference the document attribute 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 in the base.. If you want to assign his _id, before inserting it into the database, you can assign the value of the direct _id.

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

Kisses

  • thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.